I had to achieve a quite specific task and as far as I checked I didn’t find existing solutions in there so I’m gonna share my work if it helps (I really hope I’m not issuing a duplicate, I found this question Shift array to right by adding a new element to left using js which is not really my goal)
I had to insert an element in an array at a given position, and shift the rest to keep the same order and length. For example:
let array = ['a', 'b', 'd', 'e', 'f'];
const idx = 2;
const new = 'c';
Then the expected output is ['a', 'b', 'c', 'd', 'e']
The question is now: how to proceed, without creating copies and explicitly looping the whole input array ?
3
Answers
So, I came up with this solution ─ don't hesitate to tell if there's a better way to do this !
→
splice
returns an array with the removed elements: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice→
forEach
takes (element, index, array upon which forEach is called) as parameters: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEachYou could splice the array and adjust the length.
As an alternative to
Array::splice()
you can useArray::copyWithin()
: