I'm trying to find the best way to replace the last N items in an array. I'm thinking of the following:
Remove the N amount of items from the array:
arr = arr.slice(-N);
Add the needed values via array.push() doing an iteration to get to the number of needed insertions like so:
for(var i=0; i<=N; i++) {
arr.push(new value);
}
Is there a more elegant solution to this?
Thanks.
A simple reverse loop would suffice like this:
for(i = arr.length - 1; i >= arr.length - N; i--) {
arr[i] = new_value;
}
Array.prototype.splice
Removes and optionally adds values to an array starting and ending at any index value.
example:
var arr = [1, 2, 3, 4];
arr.splice(-1, 1, 'a', 'b', 'c');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With