Matthew C.
—You want to insert an item into an array at a specific index. For example, inserting an item at a specific index in a to-do list.
There are various methods to insert an item into an array, broadly divided into those that change the original array and those that don’t.
splice()
MethodThe splice()
method is used to change an array by adding, removing, or replacing elements. This method modifies the original array.
const arr = ["walk the dog", "go shopping", "exercise"]; const index = 2; const value = "go to the pharmacy"; arr.splice(index, 0, value); console.log(arr); // "walk the dog", "go shopping", "go to the pharmacy", "exercise"
The first argument of the splice()
method is the start
index, which is the index at which to start changing the array. This is the only required argument. The second argument is the deleteCount
. To add elements to an array, add each element as an additional argument. The splice()
method returns an array of the deleted elements. If no elements are deleted, an empty array is returned.
If you are dealing with very large arrays, the splice()
method is most likely to perform the best as it does not need to create a new array, unlike the other methods that are described below.
If you don’t want to modify the original array, you can also make a copy of the array before using the splice()
method:
const arr = ["walk the dog", "go shopping", "exercise"]; const arrCopy = [...arr]; const index = 2; const value = "go to the pharmacy"; arrCopy.splice(index, 0, value); console.log(arrCopy); // "walk the dog", "go shopping", "go to the pharmacy", "exercise"
slice()
MethodThe slice()
method selects a portion of an array and returns a shallow copy of it. It does not modify the original array.
The slice()
method has two optional arguments: The start
argument is the zero-based index at which to start selecting a portion of the array. The end
argument is the zero-based index at which to stop selecting a portion of the array. The slice()
method extracts up to the end
argument index, it does not include the array element at the end
index.
The slice()
method can be used along with spread syntax to insert an item into an array at a specific index:
const arr = ["walk the dog", "go shopping", "exercise"]; const index = 2; const value = "go to the pharmacy"; const newArr = [...arr.slice(0, index), value, ...arr.slice(index, arr.length)]; console.log(newArr); // "walk the dog", "go shopping", "go to the pharmacy", "exercise"
You can also use a for loop to loop through each item in an array, add each item to a new array, and insert an item at a specific index:
const arr = ["walk the dog", "go shopping", "exercise"]; const index = 2; const value = "go to the pharmacy"; const newArr = []; for (let i = 0; i < arr.length; i++) { if (i === index) { newArr.push(value); } newArr.push(arr[i]); } console.log(newArr); // "walk the dog", "go shopping", "go to the pharmacy", "exercise"
reduce()
You can create a custom function that uses reduce()
to insert an element into an array at a specific index:
const arr = ["walk the dog", "go shopping", "exercise"]; const index = 2; const value = "go to the pharmacy"; function insert(array, val, ind) { return ind >= arr.length ? array.concat(val) : array.reduce( (accumulator, currentValue, i) => accumulator.concat(i === ind ? [val, currentValue] : currentValue), [], ); } console.log(insert(arr, value, index)); // "walk the dog", "go shopping", "go to the pharmacy", "exercise"
This method creates a new array; it does not change the original array.
Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “not bad” by 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.
Here’s a quick look at how Sentry handles your personal information (PII).
×We collect PII about people browsing our website, users of the Sentry service, prospective customers, and people who otherwise interact with us.
What if my PII is included in data sent to Sentry by a Sentry customer (e.g., someone using Sentry to monitor their app)? In this case you have to contact the Sentry customer (e.g., the maker of the app). We do not control the data that is sent to us through the Sentry service for the purposes of application monitoring.
Am I included?We may disclose your PII to the following type of recipients:
You may have the following rights related to your PII:
If you have any questions or concerns about your privacy at Sentry, please email us at compliance@sentry.io.
If you are a California resident, see our Supplemental notice.