Is there an easy way to make nested array flat?

后端 未结 12 1470
执笔经年
执笔经年 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: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.

提交回复
热议问题