How to easily truncate an array with JavaScript?

后端 未结 6 1233
被撕碎了的回忆
被撕碎了的回忆 2020-12-02 16:09

Linq has a convenient operator method called Take() to return a given number of elements in anything that implements IEnumerable. Is there anything

相关标签:
6条回答
  • 2020-12-02 16:41

    Set .length property to a lower value.

    Official documentation: Array.prototype.length

    0 讨论(0)
  • 2020-12-02 16:43

    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.

    0 讨论(0)
  • 2020-12-02 16:51

    (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"
    
    0 讨论(0)
  • 2020-12-02 16:53

    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(", "));
    
    0 讨论(0)
  • 2020-12-02 16:54

    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

    0 讨论(0)
  • 2020-12-02 16:55

    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.

    0 讨论(0)
提交回复
热议问题