Is there an easy way to make nested array flat?

后端 未结 12 1471
执笔经年
执笔经年 2020-12-29 09:42

That is to make this:

[ [\'dog\',\'cat\', [\'chicken\', \'bear\'] ],[\'mouse\',\'horse\'] ]

into:

[\'dog\',\'cat\',\'chicken\',\'

相关标签:
12条回答
  • 2020-12-29 10:14

    The easiest way of flattening the Objects of any depth would be using the flat method

    var arr = [['dog','cat', ['chicken', 'bear']],[['mouse','horse'],'lion'] ]; 
    var flattened = arr.flat(Infinity);
    //output--> ["dog", "cat", "chicken", "bear", "mouse", "horse", "lion"]
    

    More aout Flat()

    0 讨论(0)
  • 2020-12-29 10:18

    Now in 2019 you can easily use Array.flat with whatever depth you want.

    let arr  = [ ['dog','cat', ['chicken', 'bear'] ],['mouse','horse'] ]
    
    let op = arr.flat(Infinity)
    
    console.log(op)

    Now if you want to get unique values you can combine both Set and flat

    let arr  = [ ['dog','cat', ['chicken', 'bear', 'cat'] ],['mouse','horse', 'dog'], [[[['deeper','chicken']]]] ]
    
    let unique  = [...new Set(arr.flat(Infinity))]
    
    console.log(unique)
    Browser comparability Except IE all other seems to support for IE you can use polyfill.

    0 讨论(0)
  • 2020-12-29 10:19

    What about this one liner code ?

    console.log([['dog', 'cat', ['chicken', 'bear']], [['mouse', 'horse'], 'lion']].join().split(','));

    basically join will make comma separated string from nested array and using split you can get 1d array, nice ? bonus it'll work on all major browsers as well :)

    0 讨论(0)
  • 2020-12-29 10:22

    In modern browsers you can do this without any external libraries in a few lines:

    Array.prototype.flatten = function() {
      return this.reduce(function(prev, cur) {
        var more = [].concat(cur).some(Array.isArray);
        return prev.concat(more ? cur.flatten() : cur);
      },[]);
    };
    
    console.log([['dog','cat',['chicken', 'bear']],['mouse','horse']].flatten());
    //^ ["dog", "cat", "chicken", "bear", "mouse", "horse"]
    
    0 讨论(0)
  • 2020-12-29 10:22

    Small fix for ChewOnThis_Trident solution and it works perfect:

    Array.prototype.flatten = function() {
        return this.reduce(function(a, b) {
            return a.concat(b);
        }, []);
    };
    
    0 讨论(0)
  • 2020-12-29 10:24

    Grab underscore.js and use the flatten function.

    _.flatten([ ['dog','cat', ['chicken', 'bear'] ],['mouse','horse'] ]);
    
    0 讨论(0)
提交回复
热议问题