29

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.

4
  • 1
    push() adds it to the end. concat() can add to the start or end, depending on how you call it... you can always origArr.slice().doSomethingMutative() also... old.concat(newer) vs newer.concat(old) Commented May 12, 2016 at 23:09
  • Thank you! I'll check it out.. EDIT: I meant to ask about unshift, sorry about that. Commented May 12, 2016 at 23:11
  • 3
    far from stupid, it's a decent question... Commented May 12, 2016 at 23:14
  • array.toSpliced returns a new array without modifying the original array doc eg. const oriArr = [1, 2, 3]; const newItem = 12; const newArr = oriArr.toSpliced(0, 0, newItem); // [12, 1, 2, 3] Commented Aug 15 at 5:03

1 Answer 1

54

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);

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.