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!
- Getting Started with Solid
- Getting Started with Svelte
- Create an RSS Reader in Node
- How to Set Up Cron Jobs in Linux
- How to build a Discord bot using TypeScript
- How to deploy a MySQL Server using Docker
- Getting Started with Sass
- Getting Started with Handlebars.js
- Getting User Location using JavaScript's Geolocation API
- Creating a Twitter bot with Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with React