jquery - How to insert an item into an array at a specific index (JavaScript)

ID : 118

viewed : 382

Tags : javascriptjqueryarraysjavascript





Top 5 Answer for jquery - How to insert an item into an array at a specific index (JavaScript)

vote vote

90

You want 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] = "Kai Jim"; arr[4] = "Borge";  console.log(arr.join()); // Jani,Hege,Stale,Kai Jim,Borge arr.splice(2, 0, "Lene"); console.log(arr.join()); // Jani,Hege,Lene,Stale,Kai Jim,Borge

vote vote

90

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

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

Then you can use it like:

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

73

Other than splice, you can use this approach which will not mutate the original array, but it will create a new array with the added item. You should usually avoid mutation whenever possible. I'm using the ES6 spread operator here.

const items = [1, 2, 3, 4, 5]  const insert = (arr, index, newItem) => [   // part of the array before the specified index   ...arr.slice(0, index),   // inserted item   newItem,   // part of the array after the specified index   ...arr.slice(index) ]  const result = insert(items, 1, 10)  console.log(result) // [1, 10, 2, 3, 4, 5]

This can be used to add more than one item by tweaking the function a bit to use the rest operator for the new items, and spread that in the returned result as well:

const items = [1, 2, 3, 4, 5]  const insert = (arr, index, ...newItems) => [   // part of the array before the specified index   ...arr.slice(0, index),   // inserted items   ...newItems,   // part of the array after the specified index   ...arr.slice(index) ]  const result = insert(items, 1, 10, 20)  console.log(result) // [1, 10, 20, 2, 3, 4, 5]

vote vote

61

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; }; 

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"] 

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; }; 

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" 

DEMO: http://jsfiddle.net/UPphH/

vote vote

55

If you want to insert multiple elements into an array at once check out this Stack Overflow answer: A better way to splice an array into an array in javascript

Also here are some functions 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; } 

Finally here is a jsFiddle so you can see it for yourself: http://jsfiddle.net/luisperezphd/Wc8aS/

And this is how you use the functions:

// if you want to insert specific values whether constants or variables: insertAt(arr, 1, "x", "y", "z");  // OR if you have an array: var arrToInsert = ["x", "y", "z"]; insertArrayAt(arr, 1, arrToInsert); 

Top 3 video Explaining jquery - How to insert an item into an array at a specific index (JavaScript)







Related QUESTION?