How to flatten array in jQuery?

后端 未结 10 765
感动是毒
感动是毒 2020-12-03 02:34

How to simply flatten array in jQuery? I have:

[1, 2, [3, 4], [5, 6], 7]

And I want:

[1, 2, 3, 4, 5, 6, 7]
相关标签:
10条回答
  • 2020-12-03 03:12

    You need arr.flat([depth])

    var arr1 = [1, 2, [3, 4]];
    arr1.flat(); 
    // [1, 2, 3, 4]
    
    var arr2 = [1, 2, [3, 4, [5, 6]]];
    arr2.flat();
    // [1, 2, 3, 4, [5, 6]]
    
    var arr3 = [1, 2, [3, 4, [5, 6]]];
    arr3.flat(2);
    // [1, 2, 3, 4, 5, 6]
    
    0 讨论(0)
  • 2020-12-03 03:13

    Use the power of JavaScript:

    var a = [[1, 2], 3, [4, 5]];
    
    console.log( Array.prototype.concat.apply([], a) );
    //will output [1, 2, 3, 4, 5]
    
    0 讨论(0)
  • 2020-12-03 03:13

    Old question, I know, but...

    I found this works, and is fast:

    function flatten (arr) {
      b = Array.prototype.concat.apply([], arr);
      if (b.length != arr.length) {
        b = flatten(b);
      };
    
      return b;
    }
    
    0 讨论(0)
  • 2020-12-03 03:15

    You can use jQuery.map():

    callback( value, indexOrKey )The function to process each item against. The first argument to the function is the value; the second argument is the index or key of the array or object property. The function can return any value to add to the array. A returned array will be flattened into the resulting array. Within the function, this refers to the global (window) object.

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