How to Insert into Array at an Index Without Mutation in JavaScript
Most array insert methods require modifying the original array, but how can we avoid mutation and return a new array with the inserted element?
Insert With Mutation
We know we can use splice()
to insert items into an array at some specified index.
let arr = ["one", "two", "four"];
arr.splice(2, 0, "three");
console.log(arr); // ["one", "two", "three", "four"]
Insert Without Mutation
We can create an insert()
function that will use the ES6 spread operator to insert the array items around the inserted item.
const insert = (arr, index, ...newItems) => [
...arr.slice(0, index),
...newItems,
...arr.slice(index)
];
arr.slice(0, index)
is grabbing the array elements before the specified index.
arr.slice(index)
is grabbing the array elements after the specified index.
Suppose we have ...arr
. The ...
, or spread operator, will “drop” the array arr
and instead return its values.
const arr1 = ["one", "two", "four"];
const arr2 = insert(arr1, 2, "three");
console.log(arr2); // ["one", "two", "three", "four"]
We can also insert multiple elements at once.
const arr1 = ["one", "two", "five"];
const arr2 = insert(arr1, 2, "three", "four");
console.log(arr2); // ["one", "two", "three", "four", "five"]