How can I remove everything except the last N elements from an array?

I have an array. I have a variable that shows how many elements in the array should be left at the end. Is there a function that will do this? Example:

var arr = [1, 2, 3, 4, 5]; var n = 2; arr = someFunction(n); // arr = [4, 5]; 

I need an array with the last n elements in it.

+6
source share
1 answer

The slice method is what you want. It returns a new object, so you must replace the existing object with a new one.

 arr = arr.slice(-1 * n); 

Alternatively, modify the existing array with splice() .

 arr.splice(0, arr.length - n); 

Splice is more efficient since it does not copy elements.

+16
source

Source: https://habr.com/ru/post/951900/


All Articles