;

How to Insert an Item into an Array at a Specific Index


Tutorialsrack 29/11/2021 Jquery Javascript

In this article, you’ll learn how to insert an item into an array at a specific index. In Javascript,  We have some in-built methods to add elements at the beginning and end of the array. But there is no built-in method to add an element to the specific index; there is no method available in the Array object. 

You can use the splice() method to insert an item into an array at a specific index in JavaScript. 

The array.splice() method can be used to add an element anywhere in an array - start, end, middle, and anywhere else in-between. 

This method takes three arguments: 

  • startIndex: the index where the element id should be inserted or removed, 
  • deleteCount: the number of items that should be deleted, 
  • Items: and the new items that should be inserted.

To add elements to an array using this splice() method, set the deleteCount to 0, and specify at least one new element.

Let's take an example to understand this:

Example - Insert an Item into an Array at a Specific Index
var persons = ["Tom", "Clark", "John"];

// Insert an item at 1st index position
persons.splice(1, 0, "Alice");
console.log(persons); 
// Output=> ["Tom", "Alice", "Clark", "John"]

// Insert multiple elements at 3rd index position
persons.splice(3, 0, "Ethan", "Peter");
console.log(persons); 
// Output=> ["Tom", "Alice", "Clark", "Ethan", "Peter", "John"]

// Insert multiple elements at 5th index position
persons.splice(5, 0, "Rocky");
console.log(persons); 
// Output=> ["Tom", "Alice", "Clark", "Ethan", "Peter", "Rocky", "John"]

I hope this article will help you to understand how to remove empty elements from an array in javascript.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags