How to easily truncate an array with JavaScript?
Linq has a convenient operator method called Take()
to return a given number of elements in anything that implements IEnumerable
. Is there anything similar in jQuery for working with arrays?
Or, asked differently: how can I truncate an array in Javascript?
There is a slice method
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
arr = arr.slice(0, 4);
console.log(arr);
Will return the first four elements.
Don't forget to assign it back to your variable if you want to discard the other values.
Note: This is just regular javascript, no need for jquery.
(2 years later...) If you're truly looking to truncate an array, you can also use the length
attribute:
var stooges = ["Moe", "Larry", "Shemp", "Curly", "Joe"];
stooges.length = 3; // now stooges is ["Moe", "Larry", "Shemp"]
Note: if you assign a length which is longer than current length, undefined array elements are introduced, as shown below.
var stooges = ["Moe", "Larry", "Shemp"];
stooges.length = 5;
alert(typeof stooges[4]); // alerts "undefined"
EDIT:
As @twhitehead mentioned below, the addition of undefined elements can be avoided by doing this:
var stooges = ["Moe", "Larry", "Shemp"];
stooges.length = Math.min(stooges.length, 5);
alert(stooges.length)// alerts "3"