Is there an easy way to make nested array flat?

后端 未结 12 1554
执笔经年
执笔经年 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: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"]
    

提交回复
热议问题