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.
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.
JavaScript Array delete() Using delete leaves undefined holes in the array. Use pop() or shift() instead.
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.
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.
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