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
Run code snippetEdit code snippet Hide Results Copy to answer Expand
UPDATE (24 May 2024)
You can now use the toSpliced method which behaves just like splice, however it returns a new array without mutating the existing one.
You could update the previous example like so:
const updated = arr.toSpliced(2, 0, "Lene");
Answer from tvanfosson on Stack OverflowYou 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
Run code snippetEdit code snippet Hide Results Copy to answer Expand
UPDATE (24 May 2024)
You can now use the toSpliced method which behaves just like splice, however it returns a new array without mutating the existing one.
You could update the previous example like so:
const updated = arr.toSpliced(2, 0, "Lene");
You can implement the Array.insert method by doing this:
Array.prototype.insert = function ( index, ...items ) {
this.splice( index, 0, ...items );
};
Then you can use it like:
var arr = [ 'A', 'B', 'E' ];
arr.insert(2, 'C', 'D');
// => arr == [ 'A', 'B', 'C', 'D', 'E' ]
I have an array of, let's say, book pages sorted by chapter. I want to insert a new page every time a page's chapter is different from the previous.
The only way I know how to do that is to create a new empty array and then iterate through my books with Array.forEach() to push into that new array. I don't like it because you shouldn't need to rewrite a book just to add pages. What if instead of a book it was a shelf of books and I wanted to insert something between the books, should I buy a second shelf from Ikea just for that?
This basically:
(page, array) => { if(page.chapter.id !== array[index - 1].chapter.id) { return [page.chapter, page]}}
I tried Array.reduce but the accumulator is a nightmare to push. It just doesn't want to be iterable and I understand that reducers de-arrays the thing.
I tried array.map but I didn't manage to return two elements (the chapter page and the first page of that chapter). I think it messes with the index.