JS implements array flattening (ES6 implementation)----examples + difficulty analysis

Requirements :

  • Take out all the elements in the nested array (multi-dimensional) and put them into a new array (one-dimensional)
  • For example: [1, [3, [2, 4]]] ==> [1, 3, 2, 4]

Basic knowledge :

arr.concat()

Syntax: array.concat(other array) Function: splice other arrays and arrays together Return value: spliced ​​new array

//准备一个原始数组
var arr=[4,6,8,2,33]
//输出一次
console.log(arr)
//执行 concat 方法
var res=arr.concat([100,200])

console.log(arr)
console.log(res) // [4, 6, 8, 2, 33, 100, 200]

ES6 implementation: some and... and concat

function flatten(arr) {
  while(arr.some(item => item instanceof Array)) {
    arr = [].concat(...arr)
  }
  return arr
}
let arr = [1, 2, [3, 4], [5, 6]]
console.log(flatten(arr)); // [1, 2, 3, 4, 5, 6]

Difficulties in understanding: [].concat(…arr)

You give it a try

let arr = [1, 2, [3, 4], [5, 6]]
console.log([].concat(...arr)) // [1, 2, 3, 4, 5, 6]

...will split arr into 1 2 [3, 4] [5, 6]

Concat will concatenate values ​​and arrays, such as [] and 1 ⇒ [1] [1] and [3, 4] ⇒ [1, 3, 4]

 

Guess you like

Origin blog.csdn.net/CaptainDrake/article/details/132523274