Insert multiple values into an array in JavaScript
This post will discuss how to insert multiple values into an array in JavaScript.
1. Using ES6 Spread operator with slicing
The recommended approach is to use the ES6 Spread operator with slicing for inserting multiple values into an array. The idea is to split the array into two subarrays using the index where specified values need to be inserted. Then we insert the specified values between the two subarrays with the help of the Spread operator. The following code example shows how to implement this.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
function insert(arr, index, ...items) { return [ ...arr.slice(0, index), ...items, ...arr.slice(index) ]; } var arr = [3, 4, 5]; var result = insert(arr, 0, 1, 2); console.log(result); /* Output: [ 1, 2, 3, 4, 5 ] */ |
2. Using Array.prototype.splice() function
Alternatively, you can use the splice() method, which can change the array’s contents by adding new elements in-place. Here’s what the code would look like:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
function insert(arr, index, ...items) { var subarray = arr.slice.call(items); arr.splice.apply(arr, [index, 0].concat(subarray)); } var arr = [3, 4, 5]; insert(arr, 0, 1, 2); console.log(arr) /* Output: [ 1, 2, 3, 4, 5 ] */ |
Note that the code modifies the original array, and no copy is made. The code can be simplified using the Spread operator:
|
1 2 3 4 5 6 7 8 9 10 11 |
function insert(arr, index, ...items) { arr.splice(arr, index, ...items); } var arr = [3, 4, 5]; insert(arr, 0, 1, 2); console.log(arr); /* Output: [ 1, 2, 3, 4, 5 ] */ |
3. Using Array.prototype.push() function
To add elements at the end of an array, you can use the push() method with spread syntax.
|
1 2 3 4 5 6 7 8 9 10 11 |
function insert(arr, ...items) { arr.push(...items); } var arr = [ 1, 2, 3, 4 ]; insert(arr, 5, 6, 7); console.log(arr); /* Output: [ 1, 2, 3, 4, 5, 6, 7 ] */ |
4. Using Array.prototype.unshift() function
Similarly, to add elements at the beginning of an array, you can use the unshift() method with spread syntax.
|
1 2 3 4 5 6 7 8 9 10 11 |
function insert(arr, ...items) { arr.unshift(...items); } var arr = [ 4, 5, 6, 7 ]; insert(arr, 1, 2, 3); console.log(arr); /* Output: [ 1, 2, 3, 4, 5, 6, 7 ] */ |
That’s all about inserting multiple values into an array in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)