Asked : Nov 17
Viewed : 30 times
I am 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.
Nov 17
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
answered Jan 13
There is no support of such functionality in lodash : see issue.
If you still want it to look like done with lodash, then you can do it like this way.
fields = [{name: 'john'},
{name: 'jane'},
{name: 'saske'},
{name: 'jake'},
{name: 'baki'}
];
_.insert = function (arr, index, item) {
arr.splice(index, 0, item);
};
_.insert(fields,2,{'name':'ace'});
console.log(fields);
answered Jan 13
That’s all about inserting an item at a specific index in an array using JavaScript., This post will discuss how to insert an item at a specific index in an array using JavaScript., The following code demonstrates how to use the splice() method to insert an item at the specified index in the array:, The splice solution modifies the original array. If you don’t want to change the original array, create a new array using the ES6 Spread operator with slicing.
The splice() method can be used to modify the array by removing or replacing existing elements and/or adding new elements in place.
The following code demonstrates how to use the splice()
method to insert an item at the specified index in the array:
splice()
Array.prototype.push()
functionTo add elements at the end of an array, you can use the push()
method.
push()
answered Jan 13
In JavaScript, it's not advisable to loop through an Array with a for-in loop, but it's better to use a for
loop such as:
for(var i=0, len=myArray.length; i < len; i++){}
It's optimized as well ("caching" the array length). If you'd like to learn more, read my post on the subject.
answered Jan 13