How to Insert Item Into JS Array At Specific Index

Web developers commonly use JavaScript arrays to store data. They are very popular, offer lots of features and are easy to use. Often, we need to insert one or more items into existing JavaScript arrays. There are several ways to do this using JavaScript. In this article, we will learn how to insert item into JS array at specific index.

How to Insert Item Into JS Array At Specific Index

Let us say you have a simple JavaScript array.

a = [1, 2, 3, 4, 5];

Let us look at some of the easy to ways to insert item into a JS array, at specific index.

1. Using Splice

Splice() is a popular JS function that adds/removes items from an array. It modifies the original array instead of creating a new array. Here is its syntax.

array.splice(index, count, item1, item2, ...)

In the above code, index is the position where we want to add/remove one or more items. It starts from 0. Negative value will start the index from end. Count is an optional argument for the number of items to be removed Thereafter, you can provide one or more items in a comma-separated manner, to be added.

Depending on the values supplied, splice() function will first remove count number of items at index, and insert the specified items at the same position.

Since we only want to insert item at specific index, we mention count=0. Here is an example to insert item=6 at position=3.

a.splice(3, 0, 6); 
console.log(a); // output is [1, 2, 3, 6, 4, 5]

If you want to insert multiple items, say, 6, 8, 9, then mention them one after the other, in a comma-separated manner.

a.splice(3, 0, 6, 8, 9); 
console.log(a); // output is [1, 2, 3, 6, 8, 9, 4, 5]

2. Using toSpliced

As mentioned above, splice() function will modify the original array. If you do not want that to happen, and want the result to be stored in a new array, then you can use toSpliced() function. Its syntax is exactly same as that of splice() function. You can use it to add/remove one or more items in an array. Here is its syntax.

array.toSpliced(index, count, item1, item2, ...)

In the above code, we need to specify the index position as the first argument. It starts from 0. Like splice(), using negative value starts the count from end. Thereafter, you need to mention the count of items to be removed. It is optional. We we will mention it as 0, since we need to insert and not remove items from our array. After that, you can specify the items to be inserted, one after the other, in a comma-separated manner.

Here is an example to insert item=6 at position=3.

b=a.toSpliced(3,0,6)
console.log(b); // [1, 2, 3, 6, 4, 5]
console.log(a); // [1, 2, 3, 4, 5]

As you can see above, the original array a remains unchanged. Its result is stored in another array b.

You can also use toSpliced() function to insert multiple items.

b=a.toSpliced(3,0,6,8,9)
console.log(b); // [1, 2, 3, 6, 8, 9, 4, 5]
console.log(a); // [1, 2, 3, 4, 5]

3. Using Prototype Function

You can use either of the above mentioned functions to create a prototype function that inserts one or more items at a given index position in an array.

Array.prototype.insert = function ( index, ...items ) {
this.splice( index, 0, ...items );
};

In the above code, we have created prototype function insert(), that accepts 2 arguments – index position and a comma-separated list of items (…item). Please note, we have used spread operator (…) to accommodate one or more items. We have already set count=0 in splice() function. Here is how to use it.

a.insert(3, 6);
console.log(a); // output is [1, 2, 3, 6, 4, 5]

Once you have defined the above prototype function, you can directly call it on all arrays on your web page.

If you do not want to modify the original array but want to store result in a new array, then you can use toSpliced() function.

Array.prototype.insert = function ( index, ...items ) {
return this.toSpliced( index, 0, ...items );
};

b = a.insert(3, 6);
console.log(b); // [1, 2, 3, 6, 4, 5]
console.log(a); // [1, 2, 3, 4, 5]

4. For pre ES6 browsers

All the above solutions work for ES6 compliant web browsers, that is, modern web browsers. However, if you or your users use very old web browsers that are pre-ES6, then you will need to use a different approach. In this case, you can slice() function that allows you to split an array. You can directly call it on all arrays. Here is its syntax.

array.slice(start_index, end_index);

In the above code, we need to specify the start and end index positions. If you use negative indexes, then JavaScript will start counting from the end. If no end index is specified, then the default is the last position.

We will use this function to insert an item into an array.

function insert(array, index) {
const items = Array.prototype.slice.call(arguments, 2);
return [].concat(array.slice(0, index), items, array.slice(index));
}

In the above function, we take 2 arguments – the array and index. In fact, the index itself contains the index position to be inserted as well as the items to be inserted. We call slice() function on the arguments keyword that stores the input arguments as an array, to get the item value(s) presend after secodnd argument. First, we extract items from the input arguments. Please note, we could have used spread operator to supply items (…items) as the 3rd argument of insert function but spread operator is supported only in ES6 browsers.

Then we use concat() function to concatenate the part of array before index, the item to be inserted and the part of array after the index. We use slice() function twice – to get the part of array from beginning to index position, and to get the part of array from the index till the end.

You can call the insert() function as shown.

b=insert(a, 3, 6);
console.log(b); // [1, 2, 3, 6, 4, 5]
console.log(a); // [1, 2, 3, 4, 5]

You can also call this function with multiple items.

b=insert(a, 3, 6, 8);
console.log(b); // [1, 2, 3, 6, 8, 9, 4, 5]
console.log(a); // [1, 2, 3, 4, 5]

5. Using Spread Operator

Spread operator is a versatile operator in JavaScript that allows you to easily concatenate arrays. It is also used to easily copy part of array or object into another array or object. It is also used for deconstructing arrays but that is not relevant here. It is supported by all ES6 web browsers and can be easily used to insert one or more items into a JS array at specific index.

function insert(array, index, new_items)
{
return [...array.slice(0, index), ...new_items, ...array.slice(index)];
}

In the above code, function insert() accepts 3 arguments – the original array, the index position to insert item, and the actual item(s) to be inserted. We use slice() function mentioned earlier to extract part of array from start to index position. We also use slice() function to extract part of array from index position to end of array. Lastly, we use spread operator to concatenate the first part of array, new items and the last part of array.

You can use it as shown below.

b=insert(a, 3, [6]);
console.log(b); // [ 1, 2, 3, 6, 4, 5 ]
console.log(a); // [ 1, 2, 3, 4, 5 ]

Please note, in the above code, you need to pass the item(s) to be inserted as array. So this is very useful if the item you want to insert itself is an array. It will seamlessly insert all items of the array into original array.

If you want to simply mention them in a comma-separated manner, you can use slice() function on arguments array to extract the items.

function insert(array, index)
{
const items = Array.prototype.slice.call(arguments, 2);
return [...array.slice(0, index), ...items, ...array.slice(index)];
}
b=insert(a, 3, 6, 8, 9);
console.log(b); // [ 1, 2, 3, 6, 8, 9, 4, 5 ]
console.log(a); // [ 1, 2, 3, 4, 5 ]

Conclusion

In this article, we have learnt how to insert item in a JavaScript array at specific index. We have tried to cover several diverse use cases instead of providing multiple ways of doing the same thing. Please note, although we have used numerical array for all our examples, they can be used for all data types in an array. You can use any of these solutions depending on your requirement.

Also read:

What Does Strict Do in JavaScript?
How to Check If Array Includes Value in JavaScript
How to Move Element to Other Element in jQuery

Leave a Reply

Your email address will not be published. Required fields are marked *