javascript tutorial - [Solved-5 Solutions] How to insert an item into an array at a specific index ? - javascript - java script - javascript array



Problem:

We are looking for a Javascript array insert method, in the style of: arr.insert(index, item) Preferably in jQuery, but any Javascript implementation will do at this point.

Solution 1:

What we want is the splice function on the native array object. arr.splice(index, 0, item); will insert item into arr at the specified index (deleting 0 items first, that is, it's just an insert). In this example we will create an array and add an element to it into index 2:

var arr = [];
arr[0] = "Jani";
arr[1] = "Hege";
arr[2] = "Stale";
arr[3] = "Kawe Jim";
arr[4] = "Borge";

console.log(arr.join());
arr.splice(2, 0, "Lene");
console.log(arr.join());
click below button to copy the code. By JavaScript tutorial team

The output of the code above will be:

Jani,Hege,Stale,Kawe Jim,Borge
Jani,Hege,Lene,Stale,Kawe Jim,Borge

click below button to copy the code. By JavaScript tutorial team

Solution 2:

We can implement the Array.insert method by doing this:

Array.prototype.insert = function ( index, item ) {
    this.splice( index, 0, item );
};
click below button to copy the code. By JavaScript tutorial team

Then we can use it like:

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

// => arr == [ 'A', 'B', 'C', 'D', 'E' ]
click below button to copy the code. By JavaScript tutorial team

Solution 3:

Custom array insert methods

1. With multiple arguments and chaining support

/* Syntax:
   array.insert(index, value1, value2, ..., valueN) */

Array.prototype.insert = function(index) {
    this.splice.apply(this, [index, 0].concat(
        Array.prototype.slice.call(arguments, 1)));
    return this;
};
click below button to copy the code. By JavaScript tutorial team

It can insert multiple elements (as native splice does) and supports chaining:

["a", "b", "c", "d"].insert(2, "X", "Y", "Z").slice(1, 6);
// ["b", "X", "Y", "Z", "c"]

click below button to copy the code. By JavaScript tutorial team

2. With array-type arguments merging and chaining support

/* Syntax:
   array.insert(index, value1, value2, ..., valueN) */

Array.prototype.insert = function(index) {
    index = Math.min(index, this.length);
    arguments.length > 1
        && this.splice.apply(this, [index, 0].concat([].pop.call(arguments)))
        && this.insert.apply(this, arguments);
    return this;
};
click below button to copy the code. By JavaScript tutorial team

It can merge arrays from the arguments with the given array and also supports chaining:

["a", "b", "c", "d"].insert(2, "V", ["W", "X", "Y"], "Z").join("-");
// "a-b-V-W-X-Y-Z-c-d"
click below button to copy the code. By JavaScript tutorial team

Solution 4:

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;
}
click below button to copy the code. By JavaScript tutorial team

And this is how we use the functions:

// 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);
click below button to copy the code. By JavaScript tutorial team

Solution 5:

This:

var arr= ["India","China","Japan","USA"];

arr.splice(index, 0, item);
click below button to copy the code. By JavaScript tutorial team

Will insert item into arr at the specified index (deleting 0 items first, that is, it's just an insert).


Related Searches to javascript tutorial - How to insert an item into an array at a specific index ?