Remove all items after an index
Though assigning a shorter value to the array length(as @dandavis said) is the fastest and simplest way to remove trailing element from an array, you can also do that using a similar method like splice which is known as slice. Like following:
array = ['mario', 'luigi', 'kong'];
array = array.slice(0, 2); //Need to assign it to the same or another variable
console.log(array); //["mario", "luigi"]
As you can see you need to store the returned value from slice
method. To understand 'why', here are the major distinction between slice
and splice
method:
- The
splice()
method returns the removed item(s) in an array andslice()
method returns the selected element(s) in an array, as a new array object. - The
splice()
method changes the original array andslice()
method doesn’t change the original array.
Use Array.length
to set a new size for an array, which is faster than Array.splice
to mutate:
var array = ['mario','luigi','kong', 1, 3, 6, 8];
array.length=2;
alert(array); // shows "mario,luigi";
Why is it faster? Because .splice
has to create a new array containing all the removed items, whereas .length
creates nothing and "returns" a number instead of a new array.
To address .splice
usage, you can feed it a negative index, along with a huge number to chop off the end of an array:
var array = ['mario','luigi','kong'];
array.splice(-1, 9e9);
alert(array); // shows "mario,luigi";