How to flatten array in jQuery?

后端 未结 10 807
感动是毒
感动是毒 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: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 ]
    

提交回复
热议问题