How to Add Item to Array at Specific Index in JavaScript
Table of Contents
When you are working with an array and want to add an element, it is easy to add it to the start and end of an array, there are built-in functions for that.
However, what if you want to add an element to a specific index in an array?
In this post, we'll learn how to add an item to a specific index you want in the array in JavaScript.
How to add an item to a specific index in an array
First, let's start with our example element and array:
JAVASCRIPTconst element = "element";
const array = ["a", "b", "c", "d", "e"];
Now let's say you want to add it to the 3rd index of the array. You can do that by using the splice
method.
The splice
method can take 3 arguments, the first one is the index you want to start from, the second one is the number of elements you want to remove, and the third one is the element you want to add.
We want to start at the 3rd index so we can pass 3
as the first argument.
We don't want to delete anything, so we can pass 0
as the second argument.
And we want to add our element, so we can pass element
as the third argument.
As a result, our usage of the splice
method will look like this:
JAVASCRIPTarray.splice(3, 0, element);
Now let's look at the full code example:
JAVASCRIPTconst element = "element";
const array = ["a", "b", "c", "d", "e"];
const index = 3;
array.splice(index, 0, element);
console.log(array);
BASH["a", "b", "c", "element", "d", "e"]
Conclusion
In this post, we learned how to add an item to a specific index in an array in JavaScript.
Simply use the splice
method and pass it additional arguments to add your element in the index you specified.
Thanks for reading!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Svelte
- Getting Started with Express
- Git Tutorial: Learn how to use Version Control
- How to Serve Static Files with Nginx and Docker
- How to deploy an Express app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Getting User Location using JavaScript's Geolocation API
- Setting Up Stylus CSS Preprocessor
- How To Create a Modal Popup Box with CSS and JavaScript
- Getting Started with Moon.js