[Solved-4 Solutions] Insert an item into an array at a specific index - javascript tutorial
Problem:
How to insert an item into an array at a specific index ?
Solution 1:
arr.splice(index, 0, item); will insert item into arr at the specified index (deleting 0 items first, that is, it's simply an insert).
In this example we will create an array and add an element to it into index 2:
The output of the code above will be:
Oscar Wilde,Kurt Vonnegut,Fyodor Dostoevsky,George Orwell,Ernest Hemingway Oscar Wilde,Kurt Vonnegut,Rowling,Fyodor Dostoevsky,George Orwell,Ernest Hemingway
Read Also
Insert an item into an arraySolution 2:
To implement the Array.insert
method by doing this:
Then we can use like this:
Solution 3:
Here are two functions (insertAt, insertArrayAt) to illustrate both examples:
Here how to use the functions (insertAt, insertArrayAt):
Read Also
Unique values in an arraySolution 4:
Array.prototype.insert()
is essential for functional programming. Actually splice could have been perfect if it had returned the mutated array instead of a totally meaningless empty array.
This Array.prototype.insert() method which doesn't mutate the original array.