5

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.

2
  • Are the value you need to push all the same? Commented Sep 2, 2015 at 17:14
  • @aduch Yep. All the values to insert are the same. Commented Sep 2, 2015 at 17:14

6 Answers 6

9

A simple reverse loop would suffice like this:

for(i = arr.length - 1; i >= arr.length - N; i--) {
    arr[i] = new_value;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Your loop condition is slightly wrong, should be i >= arr.length - N since the question asked how to replace the last N items.
If N==2 and i==8 this loop will replace from 7 to 2, that is six values instead of two, right?
Oh, I see you fixed. Nice! But it is arr.length - 1 - N. Or just use N > 0 and decrement N in the loop body.
6

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');

1 Comment

I was going to suggest splice, but Tarun's answer is the most expressive :)
5

A more functional way of doing this would be to use a mixture of slice and concat.

function replaceItemsAtEnd(array, replacements) {
  var start = array.slice(0, array.length - replacements.length);
  return start.concat(replacements);
}

This has the benefit of not mutating the original array.

Using an array as the replacement items means you aren't limited to replacing with the same value either.

Comments

4

You can use the array .fill() to do this.

var arr = [1, 2, 3, 4, 5, 6];
var N = 3;

var newValue = 0;

arr = arr.fill(newValue, -1 * N);

document.getElementById("output").innerHTML  = arr;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="output"></div>

The last N elements are replaced with newValue. Please note: IE and Opera don't support this method, but you can write code that will create the method if its' lacking. See the MDN page on .fill() for the polyfill to add the method if your browser doesn't support it.

1 Comment

FWIW, Edge does support it as well (not mentioned on the MDN page yet).
0

Tarun solution was the first one that came to my mind, but I would change it slightly to avoid the situation where array length is smaller than N. So, it becomes:

  for(i = arr.length - 1; i>= 0 && N > 0; i--) {
      arr[i] = new_value;
      N--;
   }

Comments

0

How about:

var arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
var anotherArr = [1, 2, 3];

Array.prototype.splice.apply(arr, [arr.length-anotherArr.length, anotherArr.length].concat(anotherArr));

?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.