Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove all but the last N elements from an array? [closed]

Tags:

javascript

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

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

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

like image 724
titans Avatar asked Aug 16 '13 16:08

titans


People also ask

Which method removes the last element from the end of an array?

The Array pop() method is the simplest method used to remove the last element in an array. The pop() method returns the removed element from the original array.

Which method is used to remove elements without leaving holes in the array?

JavaScript Array delete() Using delete leaves undefined holes in the array. Use pop() or shift() instead.

How do you remove the last two elements of an array?

Use the splice() method to remove the last 2 elements from an array, e.g. arr. splice(arr. length - 2, 2) . The splice method will delete the 2 last elements from the array and return a new array containing the deleted elements.


1 Answers

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

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

Alternatively, modify the existing array with splice().

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

Splice is the more efficient, since it is not copying elements.

like image 126
Craig Avatar answered Oct 04 '22 04:10

Craig