I am looking for a JavaScript array insert method, in the style of:
arr.insert(index, item)
Preferably in jQuery, but any JavaScript implem
What you 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] = "Kai Jim";
arr[4] = "Borge";
console.log(arr.join());
arr.splice(2, 0, "Lene");
console.log(arr.join());
Today (2020.04.24) I perform tests for chosen solutions for big and small arrays . I tested them on MacOs High Sierra 10.13.6 on Chrome 81.0, Safari 13.1, Firefox 75.0.
For all browsers
slice
and reduce
(D,E,F) are usually 10x-100x faster than in-place solutionssplice
(AI,BI,CI) was fastest (sometimes ~100x - but it depends of array size)Tests was divided into two groups: in-place solutions (AI,BI,CI) and non-in-place solutions (D,E,F) and was perform for two cases
Tested code is presented in below snippet
jsfiddle
function AI(arr, i, el) {
arr.splice(i, 0, el);
return arr;
}
function BI(arr, i, el) {
Array.prototype.splice.apply(arr, [i, 0, el]);
return arr;
}
function CI(arr, i, el) {
Array.prototype.splice.call(arr, i, 0, el);
return arr;
}
function D(arr, i, el) {
return arr.slice(0, i).concat(el, arr.slice(i));
}
function E(arr, i, el) {
return [...arr.slice(0, i), el, ...arr.slice(i)]
}
function F(arr, i, el) {
return arr.reduce((s, a, j)=> (j-i ? s.push(a) : s.push(el, a), s), []);
}
// -------------
// TEST
// -------------
let arr = ["a", "b", "c", "d", "e", "f"];
let log = (n, f) => {
let a = f([...arr], 3, "NEW");
console.log(`${n}: [${a}]`);
};
log('AI', AI);
log('BI', BI);
log('CI', CI);
log('D', D);
log('E', E);
log('F', F);
This snippet only presents tested code (it not perform tests)
Example results for small array on chrome are below