views:

437

answers:

4

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?

+6  A: 

There is a slice method

array.slice(0, 4);

Will return the first five 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.

Bob
perfect thanks Bob.
Alan Le
Wouldnt (0,4) return the first 4 not the first 5?
Si Keep
(0, 4) returns elements in position 0, 1, 2, 3, 4 which is a total of 5.
Bob
A: 

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

If you want to keep the elements in the array, use slice

PatrikAkerstrand
+1  A: 

If you want to selectively pull elements out of an array, you can use the jQuery.Grep method.

(from the 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(", "));

ScottKoon
+2  A: 

If your asking how to truncate (modify an array by removing the 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 your asking how to retrieve a subset of an array without modifying 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 splice modifies, slice accesses. Negative numbers as first arg indicate index from the end of the array.

Chadwick