ES6

Adding an array element at different positions.

We come across situations where we need to add elements to an array at different positions which could be – at the start, at the end or in the middle. So here we are going to cover various scenarios with live code examples.

Adding element at last

To add an element in the last of an array then we can simply use the push() method.
The push() method adds one or more elements to the end of an array and returns the new length of the array.

array.push(item1, item2, ..., itemX)

Adding element at the start

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

array.unshift(item1, item2, ..., itemX)

Adding element in the middle

To add elements in the middle of an array we need to use splice() method.
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

array.splice(index, deleteCount, item1, ....., itemX)

Params:
index => The index at which to start changing the array.
deleteCount => An integer indicating the number of elements in the array to be removed.
item1, …, itemX => The elements to add to the array, beginning from start. If you do not specify any elements, splice() will only remove elements from the array.

Here we will make sure we pass deleteCount=0, because we are talking of just adding the elements.

Adding one array to another array (merging)

There 2 ways to merge an array to another:

  • using concat() method
  • using spread operator

using the concat() method to merge arrays

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

array1.concat(array2, array3, ..., arrayX)

using the spread operator to merge arrays

Es6 spread operator has various use cases but one of those is merging arrays. Spread operators make it very easy to merge arrays. Similar to concat() this method also does not change the existing arrays.

newArray= [...array1, ...array2, ...array3, so on , ...arrayX];

Let me know your thoughts