Inserting an Item into an Array at a Specific Index in Javascript
📣 Sponsor
Arrays are common data structures found in Javascript, which typically look a bit like this:
let myArray = [ 'some', 'data', 'here' ]
They act a lot like arrays found in other languages, and are relatively easy to define. Above, we have an array consisting of three items, which we’ve stored within our array, which is conveniently called myArray
.
Sometimes, though, we want to insert a new item into an array at a specific point. For example, maybe we want to insert the word new
after some
. This is known as inserting an item into an item at a specific index, and today we’re going to look at how you do that in Javascript.
Inserting an Item into an Array at a Specific Index
In Javascript, this turns out to be quite an easy operation to perform. We use the splice
method, which is a simple function that takes 3 arguments - which also lets us delete items too. Splice accepts 2 arguments if you want to delete items from your array, or 3+ if you want to add items.
splice(startIndex, deleteCount, newItem1, newItem2, newItem3...)
Only the first option is required - and the rest are optional. So splice can take the following formats:
let myArray = [ 'some', 'data', 'here' ]
myArray.splice(0); // does nothing
myArray.splice(0, 2); // Deletes two items, starting at index 0. So 'some' and 'data' are deleted
myArray.splice(1, 0, 'new'); // Deletes zero items. Adds 'new' at index 1.
myArray.splice(2, 0, 'is', 'cool') // Deletes zero items. Adds 'is', and 'cool' at index 2.
As you can see, you can add an infinite number of new items to your array using this method. It manpulates an array - so the original array is changed by this function. You don’t have to delete any items using splice
, but you can if you want. Either leaving the delete count as 0, or empty, will mean no items are deleted from your array. Any data inserted in the third argument (or any argument after the third argument) is added to the array at the specified index.
Here is another example, where we insert ‘broccoli’ into an array at index 2
:
let arr1 = [ 'potato', 'banana', 'ravioli', 'carrot' ];
// Inserts broccoli at position 2, after deleting 0 items
arr1.splice(2, 0, 'broccoli');
// Returns [ 'potato', 'banana', 'ravioli', 'brccoli', 'carrot' ]
console.log(arr1);
More Tips and Tricks for Javascript
- Javascript Comments
- How to do Everything with Javascript Arrays
- Javascript Arrays - How to Remove Duplicate Elements
- The Many Quirks of Javascript Dates
- Updating Object Key Values with Javascript
- Javascript Errors
- Javascript innerHTML
- Inserting an Item into an Array at a Specific Index in Javascript
- How fetch works in Javascript
- Javascript Promise.all() - Everything you need to know