javascript 三种数组扁平化方式
1.递归1
let givenArr = [[1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14]]]], 10]; // 1.数组扁平化 function flatten(arr) { let res = []; for (let i = 0; i < arr.length; i++) { if( Array.isArray(arr[i])){ res = res.concat(flatten(arr[i])) }else{ res.push(arr[i]) } } return res }
console.log(flatten(givenArr))
// [1, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12, 13, 14, 10]
2.递归2
let givenArr = [[1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14]]]], 10];
function flatten(arr) { let res = []; res = arr.reduce((total, prev) => { return total.concat(Array.isArray(prev) ? flatten(prev) : prev) }, []) return res; } console.log(flatten(givenArr)) // [1, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12, 13, 14, 10]
3.flat ECMA 2019 (IE全不兼容 edge 79以后)
let givenArr = [[1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14]]]], 10]; console.log(givenArr.flat(Infinity)) // [1, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12, 13, 14, 10]