171

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?

0

7 Answers 7

286

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Wouldnt (0,4) return the first 4 not the first 5?
That's actually not true. Simon Keep is correct - the .slice() method's second argument is the array position after the last element to be returned. array.slice(0, 4) would return elements 0, 1, 2, and 3 - a total of 4 elements. Think of the second argument as the cutoff point, where .slice(0, x) will return all elements from the beginning of the array, up to but not including x.
end is NOT included, then @SimonKeep is right, see MDN developer.mozilla.org/en-US/docs/JavaScript/Reference/…
Remember to assign it back to the variable, its very important as simple as it might seem
bad way, you create a new array instance, keep in mind memory usage when coding js is not a bad idea.
|
169

(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"

14 Comments

I was surprised first when I saw this in a code... But it's the best way (if you are truncating from index 0) davidwalsh.name/empty-array
What about garbage collection doing thi way?
@JonathanM Actually, null values are not introduced; the new variables are undefined, as they are declared but not assigned any value.
Amazing! It's worth to say that this method is modifying the same Array instead of creating a new Array.
To truncate to a specific length without introducing undefined elements at the end, try stooges.length = Math.min(stooges.length,5);
|
28

If you're asking how to truncate (modify an array by removing the elements from the end) then use splice:

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

If you're asking how to retrieve a subset of an array without modifying the original, then 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.

Comments

17

Set .length property to a lower value.

Official documentation: Array.prototype.length

1 Comment

to kill all elements in the array, setting length to zero is easiest.
6

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

Comments

1

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

Comments

0

If you are using a take(3), I'm going to assume the array is originally being defined as the argument 3

const result = new Array(3) 
// result = [undefined , undefined , undefined]

If you iterator only returns 2 values, or the values are filtered after the take(3) command and 1 of your values is removed the array would look like

//result = [1 , 1 , undefined]

so to truncate the array of empty elements you can use

 result.filter((value) => value !== undefined);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.