A quick Google search revealed that there are three (apparently) equally popular methods of doing this – array.splice(), array.slice() and array.length. As each of these methods can give the same result, are trivial to use and easy to understand, performance can be the sole criteria when selecting which one to use.
Assuming we have an array that is four elements long that we want to truncate to two elements:
var array_start = ['cat','mouse','dog','chicken'];
Method 1: array.slice
Our first method, array.slice, will extract the required elements (the first two) into a new array and leave the original array untouched but by overwriting the original array we have the same end result as if we had truncated it in place:
array_start = array_start.slice(0,2);
Method 2: array.splice
Our second method, array splice, will remove all but the first two elements from the array and return them (the removed elements) as a new array. The original array will no longer contain the first two elements, which is exactly what we want:
var array_removed = array_start.splice(2);
Method 3: array.length
The third and final method involves simply setting the length property of the original array. This will remove all elements above that position.
Though they each take a different approach, they all give the same end result – an array containing only two elements, ‘cat’ and ‘mouse’.
You can see these working and experiment with them in this jsFiddle.
As each approach gives the same result, which is the most efficient?
A simple jsPerf quickly reveals that, as suspected, setting the length property is easily and consistently, the fastest on all browsers followed some distance behind by splice and with slice trailing in last place. In fact, the speed improvement of length over the alternatives is so dramatic it would be very difficult to justify using anything else when truncating an array.
A final caveat with regards to Array.length
Although I stated earlier that all three of these methods “give the same end result”, that is not strictly true. One thing to look out for is if you try to “truncate” an array at a length longer than it’s current length. If we were, for example, to try and truncate our four element array at six elements then both Array.slice and Array.splice would return the same result – an unchanged array. However, Array.length would actually increase the number of elements by 2 and return an array with two empty elements appended to it, which is very likely not what is required. This can be seen in the jsFiddle.
- Array.length (developer.mozilla.org)
- Array.slice (developer.mozilla.org)
- Array.splice (developer.mozilla.org)
- jsFiddle: Truncating an array (jsfiddle.net)
- jsPerf: The fastest way to truncate an array (jsperf.com)