How to flatten array in jQuery?

后端 未结 10 764
感动是毒
感动是毒 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 02:53

    Use recursion if you have multiple levels:

    flaten = function(flatened, arr) {
        for(var i=0;i<arr.length;i++) {
            if (typeof arr[i]!="object") {
                flatened.push(arr[i]);
            }
            else {
                flaten(flatened,arr[i]);
            }
        }
        return;
    }
    
    a=[1,[4,2],[2,7,[6,4]],3];
    b=[];
    flaten(b,a);
    console.log(b);
    
    0 讨论(0)
  • 2020-12-03 02:54

    You can use jQuery.map, which is the way to go if you have the jQuery Library already loaded.

    $.map( [1, 2, [3, 4], [5, 6], 7], function(n){
       return n;
    });
    

    Returns

    [1, 2, 3, 4, 5, 6, 7]
    
    0 讨论(0)
  • 2020-12-03 03:00

    You can use Array.prototype.reduce which is technically not jQuery, but valid ES5:

    var multidimensionArray = [1, 2, [3, 4], [5, 6], 7];
    var initialValue = [];
    
    var flattened = multidimensionArray.reduce(function(accumulator, current) {
        return accumulator.concat(current);
    }, initialValue);
    
    console.log(flattened);
    
    0 讨论(0)
  • 2020-12-03 03:04

    To recursively flatten an array you can use the native Array.reduce function. The is no need to use jQuery for that.

    function flatten(arr) {
        return arr.reduce(function flatten(res, a) { 
            Array.isArray(a) ? a.reduce(flatten, res) : res.push(a);
            return res;
        }, []);
    }
    

    Executing

    flatten([1, 2, [3, 4, [5, 6]]])
    

    returns

    [ 1, 2, 3, 4, 5, 6 ]
    
    0 讨论(0)
  • 2020-12-03 03:07
    var a = [1, 2, [3, 4], [5, [6, [7, 8]]]];
    var b = [];
    
    function flatten(e,b){
        if(typeof e.length != "undefined")
        {
            for (var i=0;i<e.length;i++)
            {
                flatten(e[i],b);
            }
        }
        else
        {
            b.push(e);
        }
    }
    flatten(a,b);
    console.log(b);
    

    The flatten function should do it, and this doesn't require jQuery. Just copy all of this into Firebug and run it.

    0 讨论(0)
  • 2020-12-03 03:11

    Here's how you could use jquery to flatten deeply nested arrays:

    $.map([1, 2, [3, 4], [5, [6, [7, 8]]]], function recurs(n) {
        return ($.isArray(n) ? $.map(n, recurs): n);
    });
    

    Returns:

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

    Takes advantage of jQuery.map as well as jQuery.isArray.

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