[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:

var arr = [];
arr[0] = "Oscar Wilde";
arr[1] = "Kurt Vonnegut";
arr[2] = "Fyodor Dostoevsky";
arr[3] = "George Orwell";
arr[4] = "Ernest Hemingway";

console.log(arr.join());
arr.splice(2, 0, "Rowling");
console.log(arr.join());

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

Solution 2:

To implement the Array.insert method by doing this:

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

Then we can use like this:

var arr = [ 'A', 'B', 'D', 'E' ];
arr.insert(2, 'C');

// => arr == [ 'A', 'B', 'C', 'D', 'E' ]

Solution 3:

Here are two functions (insertAt, insertArrayAt) to illustrate both examples:

function insertAt(array, index) {
    var arrayToInsert = Array.prototype.splice.apply(arguments, [2]);
    return insertArrayAt(array, index, arrayToInsert);
}

function insertArrayAt(array, index, arrayToInsert) {
    Array.prototype.splice.apply(array, [index, 0].concat(arrayToInsert));
    return array;
}

Here how to use the functions (insertAt, insertArrayAt):

// if we want to insert specific values whether constants or variables:
insertAt(arr, 1, "x", "y", "z");

// OR if we have an array:
var arrToInsert = ["x", "y", "z"];
insertArrayAt(arr, 1, arrToInsert);

Solution 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.

Array.prototype.insert = function(i,...rest){
  this.splice(i,0,...rest)
  return this
}

var a = [3,4,8,9];
document.write("<pre>" + JSON.stringify(a.insert(2,5,6,7)) + "</pre>");

This Array.prototype.insert() method which doesn't mutate the original array.

Array.prototype.insert = function(i,...rest){
  return this.slice(0,i).concat(rest,this.slice(i));
}

var a = [3,4,8,9],
    b = a.insert(2,5,6,7);
console.log(JSON.stringify(a));
console.log(JSON.stringify(b));

Related Searches to Insert an item into an array at a specific index - javascript tutorial