add element in the middle of array javascript

Adding Element in the Middle of Array in Javascript

There may be times when you need to add an element in the middle of an array in Javascript. Here are a few ways to do so:

Using the splice() Method

The splice() method can be used to add an element to an array at a specific index. Here’s how:


let myArray = [1, 2, 4, 5];
myArray.splice(2, 0, 3); // Adds element 3 at index 2
console.log(myArray); // Output: [1, 2, 3, 4, 5]

The first parameter of the splice() method specifies the index where the element should be added. The second parameter specifies how many elements should be removed (in this case, we’re not removing anything). The third parameter specifies the element that should be added.

Using the concat() Method

The concat() method can be used to join two arrays together. Here’s how:


let myArray = [1, 2, 4, 5];
let newArray = myArray.slice(0, 2).concat(3, myArray.slice(2));
console.log(newArray); // Output: [1, 2, 3, 4, 5]

We first slice the original array to get everything up to the index where we want to add the new element. We then use concat() to join that sliced array with the new element and the rest of the original array.

Using the spread operator

The spread operator can also be used to add an element to an array at a specific index. Here’s how:


let myArray = [1, 2, 4, 5];
let newArray = [...myArray.slice(0, 2), 3, ...myArray.slice(2)];
console.log(newArray); // Output: [1, 2, 3, 4, 5]

This code also slices the original array and uses the spread operator to join the sliced arrays with the new element.

Conclusion

These are just a few ways to add an element in the middle of an array in Javascript. Each method has its own advantages and disadvantages depending on the situation. Use whichever method suits your needs.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe