Insert an item at a specific index in an array using JavaScript
This post will discuss how to insert an item at a specific index in an array using JavaScript.
1. Using Array.prototype.splice() function
The splice() method can be used to modify the array by removing or replacing existing elements and/or adding new elements in-place.
The following code demonstrates how to use the splice() method to insert an item at the specified index in the array:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Array.prototype.insert = function(index, item) { this.splice(index, 0, item); }; var arr = [ 1, 2, 4, 5 ]; const item = 3, index = 2; arr.insert(index, item); console.log(arr); /* Output: [ 1, 2, 3, 4, 5 ] */ |
2. Using ES6 Spread operator with slicing
The splice solution modifies the original array. If you don’t want to change the original array, create a new array using the ES6 Spread operator with slicing.
The idea is to split the array into two subarrays using the index where specified values need to be inserted. Then we put the specified value between two subarrays with the help of the Spread operator. Here’s what the code would look like:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
insert = function(arr, index, item) { return [ ...arr.slice(0, index), // first half item, // items to be inserted ...arr.slice(index) // second half ]; }; var arr = [ 1, 2, 4, 5 ]; const item = 3, index = 2; arr = insert(arr, index, item); 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.
|
1 2 3 4 5 6 7 8 9 |
var arr = [ 1, 2, 3, 4 ]; const item = 5; arr.push(item); console.log(arr); /* Output: [ 1, 2, 3, 4, 5 ] */ |
4. Using Array.prototype.unshift() function
Similarly, to add elements at the beginning of an array, you can use the unshift() method.
|
1 2 3 4 5 6 7 8 9 |
var arr = [ 2, 3, 4, 5 ]; const item = 1; arr.unshift(item); console.log(arr); /* Output: [ 1, 2, 3, 4, 5 ] */ |
That’s all about inserting an item at a specific index in an array using 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 :)