Inserting an item into an array at a specific index is a common operation in JavaScript. There are several ways to achieve this, each with its own use cases and advantages. In this article, we will explore different methods to insert an item into an array at a specific index, providing detailed explanations and complete code examples for each approach.
Approach 1. Using splice() Method
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
Syntax
array.splice(start, deleteCount, item1, item2, ...);
Parameters
- start: The index at which to start changing the array.
- deleteCount: The number of elements to remove (if any).
- item1, item2, …: The elements to add to the array.
Example
let numbers = [1, 2, 3, 5, 6]; let index = 3; let newItem = 4; numbers.splice(index, 0, newItem); console.log(numbers); // Output: [1, 2, 3, 4, 5, 6]
In this example, splice(3, 0, 4) inserts the number 4 at index 3 without removing any elements.
Approach 2. Using slice() and concat() Methods
The slice() method returns a shallow copy of a portion of an array into a new array object. The concat() method is used to merge two or more arrays.
Example
let arr = [10, 20, 30, 40, 50]; let index = 1; let newItem = 15; let newArray = arr.slice(0, index) .concat(newItem, arr.slice(index)); // Output: [ 10, 15, 20, 30, 40, 50 ] console.log(newArray);
In this example, slice(0, index) creates a new array from the start to the specified index, and slice(index) creates another array from the specified index to the end. The concat() method then merges these arrays with the new item in between.
Approach 3. Using Array.from() Method
The Array.from() method creates a new array instance from an array-like or iterable object. This can be combined with map() to insert a new item at a specific index.
Example
let letters = ['a', 'b', 'd', 'e']; let index = 2; let newItem = 'c'; let newArray = Array.from({ length: letters.length + 1 }, (_, i) => i === index ? newItem : i < index ? letters[i] : letters[i - 1] ); console.log(newArray); // Output: ['a', 'b', 'c', 'd', 'e']
In this example, Array.from() creates a new array of the required length, and map() inserts the new item at the specified index while shifting the rest of the elements accordingly.
Approach 4. Using Spread Operator
The spread operator (...
) allows an iterable such as an array expression or string to be expanded in places where zero or more arguments or elements are expected.
Example
let arr = [10, 20, 30, 40, 50]; let index = 1; let newItem = 15; let newArray = [ ...arr.slice(0, index), newItem, ...arr.slice(index) ]; // Output: [ 10, 15, 20, 30, 40, 50 ] console.log(newArray);
In this example, the spread operator is used to create a new array by spreading the elements before and after the specified index, with the new item inserted in between.