163

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?

KyleMit
  • 30,350
  • 66
  • 462
  • 664
Alan Le
  • 8,683
  • 7
  • 36
  • 31

7 Answers7

271

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.

danday74
  • 52,471
  • 49
  • 232
  • 283
Bob
  • 97,670
  • 29
  • 122
  • 130
  • 16
    Wouldnt (0,4) return the first 4 not the first 5? – Simon Keep Oct 28 '09 at 09:00
  • 15
    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. – Bungle Oct 26 '12 at 00:49
  • 2
    `end` is NOT included, then @SimonKeep is right, see MDN https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/slice – AsTeR Apr 06 '13 at 11:31
  • 2
    Remember to assign it back to the variable, its very important as simple as it might seem – kolexinfos Aug 01 '13 at 13:49
  • 7
    bad way, you create a new array instance, keep in mind memory usage when coding js is not a bad idea. – G. Ghez Mar 27 '15 at 16:28
  • It bears mentioning that Array.prototype.slice() will simply stop at the end of the array and return without error if the supplied end index is larger than the length of the array. This is a convenient and usually expected behavior. Messing with the length property of the array object will have give a less desirable behavior, as the answer below has described. – pscl May 25 '17 at 02:09
  • Good note, @pscl. The answer has been updated to avoid that behavior if it is not desired. – Jonathan M Jan 24 '18 at 19:37
159

(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"
Jonathan M
  • 17,145
  • 9
  • 58
  • 91
  • 6
    I was surprised first when I saw this in a code... But it's the best way (if you are truncating from index 0) http://davidwalsh.name/empty-array – kumarharsh Aug 22 '13 at 13:52
  • 3
    What about garbage collection doing thi way? – G. Ghez Mar 27 '15 at 16:23
  • @G.Ghez, no problems there. What concerns do you have? – Jonathan M May 22 '15 at 16:07
  • 2
    @JonathanM Actually, null values are not introduced; the new variables are undefined, as they are declared but not assigned any value. – Håvard Geithus Jun 15 '15 at 18:06
  • 1
    Good catch, @Håvard. Updated. – Jonathan M Jun 25 '15 at 15:15
  • 3
    Amazing! It's worth to say that this method is modifying the same `Array` instead of creating a new `Array`. – roomcayz Sep 03 '17 at 09:24
  • 1
    To truncate to a specific length without introducing undefined elements at the end, try `stooges.length = Math.min(stooges.length,5);` – twhitehead Nov 26 '17 at 18:08
  • Resetting the length seems to be way way slower than stooges = [] or stooges = null. See this jsperf https://jsperf.com/array-destroy – hitautodestruct Aug 24 '18 at 11:44
  • Hi, @hitautodestruct. Your statement may be true. However, the goal with truncating is not to empty the array, or to set it to null. Truncating is about keeping the first indices, while getting rid of the latter indices. – Jonathan M Sep 03 '18 at 02:41
  • @JonathanM You're correct. But, if you are truncating from index 0 this is very very slow and has the same effect as emptying the array. Also, slice would be better and more verbose for truncating :-) – hitautodestruct Sep 04 '18 at 13:32
  • @hitautodestruct, I would agree, but I think the heart of the OP's question was about truncating from somewhere other than index 0. As to slice being better, a definition of better would be required for me to agree. – Jonathan M Sep 05 '18 at 22:10
  • @JonathanM Well, for me, `slice` is basically what you would intuitively use for truncating an array, it's faster and more readable. But I guess better is a relative term. – hitautodestruct Sep 06 '18 at 06:40
  • @G.Ghez **The truncated are garbage-collected.** The `.length` setter actually deletes (“dereferences”) the properties. Check it out: `Object.getOwnPropertyNames(array)`. – Константин Ван May 08 '22 at 21:06
  • With `"use strict"`, I get `TypeError: setting getter-only property "length"`. – Joseph Quinsey Dec 02 '22 at 19:56
27

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.

Jacob
  • 188
  • 1
  • 4
  • 13
Chadwick
  • 12,555
  • 7
  • 49
  • 66
17

Set .length property to a lower value.

Official documentation: Array.prototype.length

Brad Koch
  • 19,267
  • 19
  • 110
  • 137
G. Ghez
  • 3,429
  • 2
  • 21
  • 18
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

PatrikAkerstrand
  • 45,315
  • 11
  • 79
  • 94
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(", "));
Pier-Luc Gendreau
  • 13,553
  • 4
  • 58
  • 69
ScottKoon
  • 3,483
  • 6
  • 27
  • 29
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);
Rex
  • 89
  • 2
  • 9