Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Array unshift() in an immutable way

How would you implement something like the Array unshift() method so that it creates a new array? Basically something like the Array concat() method but instead of placing the new item at the end, place it in the beginning.

like image 862
Vlady Veselinov Avatar asked May 12 '16 23:05

Vlady Veselinov


People also ask

Is array immutable in JavaScript?

In JavaScript, only objects and arrays are mutable, not primitive values.

What does Unshift do to an array?

unshift() The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

Can array immutable?

You can create an immutable copy of an array using Array. slice() with no arguments, or with the Array. from() method. It's considered a best practice to do so before manipulating an array.

Is array splice immutable?

splice() is not immutable. It modifies the given array.


1 Answers

You can actually accomplish this using the .concat method if you call it on an array of elements you want to put at the front of the new array.

Working Example:

var a = [1, 2, 3];  var b = [0].concat(a);  console.log(a);  console.log(b);

Alternately, in ECMAScript 6 you can use the spread operator.

Working Example (requires modern browser):

var a = [1, 2, 3]  var b = [0, ...a];  console.log(a);  console.log(b);
like image 115
Alexander O'Mara Avatar answered Sep 27 '22 18:09

Alexander O'Mara