Insert Element(s) at Specific Position in an Array in JavaScript

Author — Nitish Kumar

In one of my previous posts, I mentioned different ways to remove or delete a specific element from an array in JavaScript. When manipulating arrays, the need to insert elements at a specific index is just as common. There are multiple ways to insert elements into an array. Each of these methods has its own pros and cons. This tutorial will teach you how to choose the best method to insert elements in an array using JavaScript in certain situations.

On This Page

Insert One or Multiple Elements at a Specific Index Using Array.splice()

The JavaScript Array.splice() method is used to change the contents of an array by removing existing elements and optionally adding new elements. This method accepts three parameters. The first parameter determines the index at which you want to insert the new element or elements. The second parameter determines the number of elements that you want to delete from the original array. The third parameter is the element that you want to insert into the original array. You can also insert more than one element at once. They will be inserted one after the other consecutively.

The following examples should make the insertion process clear:

JavaScript

var colors = ["Violet", "Indigo", "Yellow", "Orange", "Red"];
colors.splice(2, 0, "Blue", "Green");

// Output — ["Violet", "Indigo", "Blue", "Green", "Yellow", "Orange", "Red"]
console.log(colors);

var colors = ["Violet", "Indigo", "Yellow", "Orange", "Red"];
colors.splice(2, 0, ["Blue", "Green"]);


// Output — ["Violet", "Indigo", ["Blue", "Green"], "Yellow", "Orange", "Red"]
console.log(colors);

In the above example, you might have noticed that the elements to be inserted into the array need to be provided separately. Otherwise, the they would be inserted as an array.

The splice() method also returns all the deleted elements as an array. This means that if you delete anything from the original array, the deleted elements can be stored in a variable.

JavaScript

var colors = ["Violet", "Indigo", "Yellow", "Orange", "Red"];
var deleted = colors.splice(2, 2, "Blue", "Green");

// Output — ["Violet", "Indigo", "Blue", "Green", "Red"]
console.log(colors);

// Output — ["Yellow", "Orange"]
console.log(deleted);

You can also provide the first parameter as a negative value. This will start the insertion from the end of the original array. The elements will be added before the given index after counting backwards. Here is an example:

JavaScript

var colors = ["Violet", "Indigo", "Yellow", "Orange", "Red"];
colors.splice(-3, 0, "Blue", "Green");

// Output — ["Violet", "Indigo", "Blue", "Green", "Yellow", "Orange", "Red"]
console.log(colors);

Insert One or Multiple Elements at a Specific Index Using the Spread Operator in ES6

The spread operator in ES6, which is written as three dots (…), can be used to expand iterables like an array or a string in places where zero or more arguments or elements are expected.

We can use this operator along with the Array.slice() method to insert one or more elements into an array at any given position. The slice() method returns a shallow copy of a portion of the calling array into a new array object selected from begin to end (end not included). The original array is not be modified.

One advantage of using this technique is that you don’t have to mutate the original array. Here is an example which shows the spread operator in action:

JavaScript

var people = ["Amanda", "Alan", "John", "Smith"];
var morePeople = [...people.slice(0, 2), "Rhonda", "Daisy", ...people.slice(2)];

// Output — ["Amanda", "Alan", "Rhonda", "Daisy", "John", "Smith"]
console.log(morePeople);

In the above example, we have used the spread operator along with two calls to the slice() method in order to create a new array with all the elements inserted into it. The first slice() method returns all elements from the beginning of the array up to index - 1 where we want to insert the new elements. The second slice() method returns all elements from the given index up to the end of the original array.

Insert One or Multiple Elements at the End of an Array Using Array.push()

If you are only planning to insert one or multiple elements at the end of an array, you don’t have to use any complicated methods. You can simply use Array.push() and specify the elements that you want to append.

Keep in mind that you will have to specify all the elements that you want to insert into the array in separate arguments. Otherwise, they will be inserted as a single array.

JavaScript

var animals = ["Monkey", "Lion", "Cow", "Crocodile"];
animals.push("Tiger", "Deer");

// Output — ["Monkey", "Lion", "Cow", "Crocodile", "Tiger", "Deer"]
console.log(animals);

The only limitation of this technique is that the elements can only be inserted at the end of the array. However, if that is what you intend to do, using push() might be more appropriate than using splice().

Insert One or Multiple Elements Before a Specific Element in an Array

Sometimes you might have to insert an element after another one with a specific value. This is slightly different from inserting elements at a certain index. In such cases, you can start by first finding the index of the element after which you want to insert the new elements. This can be done using the Array.indexOf() method. Once you have the index, you can use any of the first two methods in this post to insert the new elements into the original array.

JavaScript

var people = ["Amanda", "Alan", "John", "Smith"];
var index = people.indexOf("John");
people.splice(index, 0, "Rhonda", "Kerry");

// Output — ["Amanda", "Alan", "Rhonda", "Kerry", "John", "Smith"]
console.log(people);

One problem that can arise with the use of this technique is that the element may not exist in the array at all. In such cases, the desired behavior may differ from one project to another. With the above code, the element would be inserted just before the last element of the original array. If you want the element to be added at the end of the array, you will have to check the return value of the indexOf() method. If the value is equal to minus 1, you can just use the push() method to append the elements to the original array. The following example does exactly that:

JavaScript

var people = ["Amanda", "Alan", "John", "Smith"];
var index = people.indexOf("Jolly");

if(index > -1) {
  people.splice(index, 0, "Rhonda", "Kerry");
} else {
  people.push("Rhonda", "Kerry");
}

// Output — ["Amanda", "Alan", "John", "Smith", "Rhonda", "Kerry"]
console.log(people);

You can specify your own insertion behaviour in a similar manner.

Insert One or Multiple Elements After a Specific Element in an Array

Inserting new elements after a specific element in an array is just as easy as inserting them before the specific elements. The only modification you have to make is pass index+1 as the value of the first parameter in the splice() method.

JavaScript

var people = ["Amanda", "Alan", "John", "Smith"];
var index = people.indexOf("John");
people.splice(index + 1, 0, "Rhonda", "Kerry");

// Output — ["Amanda", "Alan", "John", "Rhonda", "Kerry", "Smith"]
console.log(people);

If you try to add new elements after some non-existing element in the original array, the above code will insert those elements at the beginning of the original array. This is because the returned index will be -1 and adding 1 to it will give us 0 as the value of the first parameter.

Quick Summary

Let’s recap everything that we have covered in this tutorial.

  1. If you want to insert one or multiple elements at a given index and do not care about changing your original array, you can simply use the Array.splice() method. One advantage of using this technique is that it will work in all major browsers.
  2. A more modern approach to insert new elements into an array includes the use of spread operator in ES6. This operator combined with the Array.slice() method can be used to insert new elements at any given index. The original array will not be modified. Unfortunately, this technique will not work in older browsers.
  3. You can insert elements at the end of an array much more efficiently using the Array.push() method. This will also return the length of new array.
  4. You can also insert a given element before or after another element with a specific value by first calculating the index of the other element using the Array.indexOf() method. Once you have the index, you can use either one of the first two methods to insert the new elements.

Let me know if there is anything that you would like me to clarify in this tutorial. Also, you are more than welcome to comment if you know other efficient techniques to insert new elements in an array in JavaScript.

Rate this post —

Very PoorPoorAverageGoodExcellent (No Ratings Yet)
Loading...
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0%