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?


Answers:


There is a slice method

array.slice(0, 4);

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.