1

I have a JS array so:

var car_type_1 = [12,16,23,31,33,34,39,45,49,54,59,62,62,62,63,63,64,66,69,71,73,75,78,80,82,85,87,89,91,94,95]; var car_type_2 = [17,20,28,35,37,38, and so on]; 

I created another array which stores the subtracted values between the consecutive numbers in the old array:

 function diff(arr) { return arr.slice(1).map(function(n, i) { return n - arr[i]; }); } var car_type_1_diff = diff(car_type_1); //so on 

Understandly, the new array has 1 less element compared to the old array. What I want to do is add the first number of the old array to the new array, so it should be like:

 car_type_1_diff = [**12**, 4, 7, 8, 2, 1, 5, 6, 4, 5, 5, 3, 0, 0, 1, 0, 1, 2, 3, 2, 2, 2, 3, 2, 2, 3, 2, 2, 2, 3, 1] 

12 should be pushed to the beginning of the new array 1. How can I do this?

2

3 Answers 3

3

In ES6, when constructing the new array car_type_1_diff you can also use the spread operator like so: var car_type_1_diff = [12, ...diff(car_type_1)]

Sign up to request clarification or add additional context in comments.

1 Comment

This is the preferred approach when compared to unshift when array mutation is not desirable and helps build more predictable applications.
2

Yes, you can use unshift method.

Example from the referenced docs:

var arr = [1, 2]; arr.unshift(0); // result of call is 3, the new array length // arr is [0, 1, 2] arr.unshift(-2, -1); // = 5 // arr is [-2, -1, 0, 1, 2] arr.unshift([-3]); // arr is [[-3], -2, -1, 0, 1, 2] 

1 Comment

Note that unshift returns an integer and mutates the array, a behavior which may be undesirable if you're shooting for immutable state.
0

Possibly you are looking for unshift() method.

1 Comment

It would be helpful to see an example usage of unshift in the answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.