Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace last N items in an array with JavaScript

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.

like image 704
cycero Avatar asked Dec 02 '22 14:12

cycero


2 Answers

A simple reverse loop would suffice like this:

for(i = arr.length - 1; i >= arr.length - N; i--) {
    arr[i] = new_value;
}
like image 144
Tarun Dugar Avatar answered Dec 09 '22 22:12

Tarun Dugar


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');
like image 43
dhudson Avatar answered Dec 09 '22 21:12

dhudson