Q:

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

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the JavaScript splice() Method

You can use the splice() method to insert a value or an item into an array at a specific index in JavaScript. This is a very powerful and versatile method for performing array manipulations.

The splice() method has the syntax like array.splice(startIndexdeleteCount, item1, item2,...). To add elements to an array using this method, set the deleteCount to 0, and specify at least one new element, as demonstrated in the following example:

<script>
    var persons = ["Harry", "Clark", "John"];
    
    // Insert an item at 1st index position
    persons.splice(1, 0, "Alice");
    console.log(persons); // Prints: ["Harry", "Alice", "Clark", "John"]
    
    // Insert multiple elements at 3rd index position
    persons.splice(3, 0, "Ethan", "Peter");
    console.log(persons); // Prints: ["Harry", "Alice", "Clark", "Ethan", "Peter", "John"]
</script>

To add items at the end or beginning of an array you can simply use the push() and unshift() array methods.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Get the ID of the Element that Fired an Eve... >>
<< How to Scroll to the Top of the Page Using jQuery/...