How to insert an item into an array at particular index in java script

139


can anyone tell if there is a method to insert an element at specific index in an array? I'm using push() method to insert elements at the end of the array but I need to insert elements at a specific index. How can I do that?

1 Answer

4 years ago by

You can insert an element into an array using splice method. Splice follows the syntax arrayName.splice(startIndex, deleteCount, item1, item2,...). For inserting elements deleteCount should be 0.

To insert a single element

Array.prototype.insert = function ( index, item ) {
    this.splice( index, 0, item );
};

let arr = [ 1, 2, 3, 5, 6];
arr.insert(3, 4);

console.log(arr);

To insert multiple elements

let array = [1, 5, 6, 7, 8, 9, 10]

let insert = (arr, index, ...newItems) => [...arr.slice(0, index), ...newItems, ...arr.slice(index)];

let newArray = insert(array, 1, 2, 3, 4);

console.log(newArray); 
4 years ago by Divya