How to insert an element into an array at a position
Short answer
splice(index, 0, item) inserts an element at the index without removing anything:
const letters = ['a', 'b', 'd'];
letters.splice(2, 0, 'c');
console.log(letters.join(', '));Output:
a, b, c, dTo the beginning
unshift() adds elements to the start of the array:
const queue = ['second', 'third'];
queue.unshift('first');
console.log(queue.join(', '));Output:
first, second, thirdWithout changing the original
toSpliced() works like splice(), but returns a new array:
const letters = ['a', 'b', 'd'];
const full = letters.toSpliced(2, 0, 'c');
console.log(letters.join(''), full.join(''));Output:
abd abcdCommon mistake
splice() returns the removed elements, not the new array. With zero removed elements the result is empty:
const letters = ['a', 'b', 'd'];
const result = letters.splice(2, 0, 'c');
console.log(result.length);Output:
0Functions used in this recipe
- Array.prototype.splice — Removes, replaces or inserts elements in the middle of an array.
- Array.prototype.toSpliced — Returns a copy of an array with elements removed, replaced or inserted.
- Array.prototype.unshift — Adds elements to the beginning of an array.