JS数组扁平化

it2025-01-16  5

数组扁平化

1、Array.prototype.flat(num)

num: 可选参数,展开嵌套层数

let ary = [1, 2, 3, [4, 5]] console.log(ary.flat()) // [ 1, 2, 3, 4, 5 ] let ary1 = [1, 2, 3, [4, 5, [6, 7]]] console.log(ary1.flat()) // [ 1, 2, 3, 4, 5, [ 6, 7 ] ] let ary2 = [1, 2, 3, [4, 5, [6, 7]]] console.log(ary2.flat(2)) // [ 1, 2, 3, 4, 5, 6, 7 ] // 参数大于层数时,展开所有嵌套 let ary3 = [1, 2, 3, [4, 5, [6, 7]]] console.log(ary3.flat(3)) // [ 1, 2, 3, 4, 5, 6, 7 ] let ary4 = [1, 2, 3, [4, 5], {name: 'tom', age: 18}] console.log(ary4.flat()) // [ 1, 2, 3, 4, 5, { name: 'tom', age: 18 } ] // 有对象嵌套时,仍然展开 let ary5 = [1, 2, 3, [4, 5, {name: 'xiao', age: 20}], {name: 'tom', age: 18}] console.log(ary5.flat()) // [ 1, 2, 3, 4, 5, { name: 'xiao', age: 20 }, { name: 'tom', age: 18 } ] let ary = [1, 2, 3, [4, 5, [6, 7, { name: 'xiao', age: 20 }]], { name: 'tom', age: 18 }] console.log(ary.flat(4)) // [ 1, 2, 3, 4, 5, 6, 7, { name: 'xiao', age: 20 }, { name: 'tom', age: 18 } ] // 对象嵌套不能展开 let ary = [1, 2, 3, [4, 5, [6, 7]], { name: 'tom', age: 18, 'key': { name: 'xiao', age: 20 } }] console.log(ary.flat(4)) // [ 1, 2, 3, 4, 5, 6, 7, { name: 'tom', age: 18, key: { name: 'xiao', age: 20 } ]

2、使用正则

let ary = [1, 2, 3, [4, 5, [6, 7]], {name: 'tom'}] const res2 = JSON.parse('[' + JSON.stringify(ary).replace(/\[|\]/g, '') + ']') console.log(res2) // [ 1, 2, 3, 4, 5, 6, 7, { name: 'tom' } ]

3、Array.prototype.reduce()

let arr = [1, 2, 3, [4, 5, [6, 7]], {name: 'tom'}] const flatten = arr => { return arr.reduce((pre, cur) => { return pre.concat(Array.isArray(cur) ? flatten(cur) : cur) }, []) } const res4 = flatten(arr); console.log(res4) // [ 1, 2, 3, 4, 5, 6, 7, { name: 'tom' } ]

4、使用函数递归

let arr = [1, 2, 3, [4, 5, [6, 7]], {name: 'tom'}] const ary = [] const fn = arr => { for (let i = 0; i < arr.length; i++) { if (Array.isArray(arr[i])) { fn(arr[i]) } else { ary.push(arr[i]) } } } fn(arr) console.log(ary) // [ 1, 2, 3, 4, 5, 6, 7, { name: 'tom' } ]
最新回复(0)