How to easily crop an array using JavaScript?

Linq has a convenient operator method called Take() to return a given number of elements in everything that implements IEnumerable . Is there something similar in jQuery for working with arrays?

+55
javascript jquery
Jun 04 '09 at 21:01
source share
6 answers

There is a slice method

 array.slice(0, 4); 

Will return the first four elements.

Remember to assign it back to your variable if you want to override other values.

Note. This is just plain javascript, without jquery.

+105
Jun 04 '09 at 21:04
source share

(2 years later ...) If you really want to truncate the 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 longer than the current length, the elements of the undefined array are entered, as shown below.

 var stooges = ["Moe", "Larry", "Shemp"]; stooges.length = 5; alert(typeof stooges[4]); // alerts "undefined" 
+79
Aug 03 2018-11-11T00:
source share

If you ask how to trim (modify the array by removing elements from the end), use splice :

 var a1 = [2,4,6,8]; var a2 = a1.splice(-2,2); // a1=[2,4], a2=[6,8] 

If you are asking how to get a subset of an array without changing the original, use slice .

 var a1 = [2,4,6,8]; var a2 = a1.slice(-2); // a1=[2,4,6,8], a2=[6,8] 

Just remember that splicing changes, cuts access. Negative numbers like the first arg indicate the index from the end of the array.

+18
Jun 04 '09 at 21:25
source share

Set the .length property to a lower value.

Official Documentation: Array.prototype.length

+8
Mar 27 '15 at 16:29
source share

If you want to both get the elements and remove them from the array, use splice .

If you want to store elements in an array, use slice

+4
Jun 04 '09 at 21:06
source share

If you want to selectively pull elements from an array, you can use the jQuery.grep method.

(from jQuery docs)

 var arr = [ 1, 9, 3, 8, 6, 1, 5, 9, 4, 7, 3, 8, 6, 9, 1 ]; $("div").text(arr.join(", ")); arr = jQuery.grep(arr, function(n, i){ return (n != 5 && i > 4); }); $("p").text(arr.join(", ")); arr = jQuery.grep(arr, function (a) { return a != 9; }); $("span").text(arr.join(", ")); 
+2
Jun 04 '09 at 21:21
source share



All Articles