js flattening of process arrays

A lot of methods, the first method is when I interviewed in bytes, asked me to write out the scene, memories

Method 1: array.reduce implemented

 1 function flatten(arr = []) {
 2   return arr.reduce((a, b) => {
 3     if (Array.isArray(b)) {
 4       return [...a, ...flatten(b)]
 5     } else {
 6       return [...a, b]
 7     }
 8   }, [])
 9 }
10 
11 var arr = [1, [2, 3], [4, 5, 6]]
12 var newArr = flatten(arr)
13 console.log(newArr)

 

Method 2: Logic normal Recursive

 

. 1  function Flatten (ARR) {
 2    the let of arr1 = []
 . 3    arr.forEach ((Val) => {
 . 4      // prototype detector is on the left of the scope chain constructor right 
. 5      IF (Val the instanceof the Array) {
 . 6        = of arr1 arr1.concat (Fn (Val))
 . 7      } the else {
 . 8        arr1.push (Val)
 . 9      }
 10    })
 . 11    return of arr1
 12 is  }
 13 is  var ARR = [. 1, 2, [. 3,. 4,. 5, [. 6 ,. 7,. 8],. 9], 10, [. 11, 12 is ]];
 14  var newArr = flatten(arr)
15 console.log(newArr) // output: 1,2,3,4,5,6,7,8,9,10,11,12

 

Method 3: apply manner

function flatten(arr = []) {
  while (arr.some(r => Array.isArray(r))) {
    arr = [].concat.apply([], arr)
  }
  return arr;
}

var arr = [1, [2, 3], [4, 5, 6]]
var newArr = flatten(arr)
console.log(newArr)

 

More ways to please Baidu, a lot of methods

Guess you like

Origin www.cnblogs.com/ajaxkong/p/12002337.html