问题
手写一个拍平数组的方法,拍成一维数组
[1, [1, 2, 3, [6, 7, 8, [10, 11, 12, 13]]], 4, 5]
-> [1, 1, 2, 3, 6, 7, 8, 10, 11, 12, 13, 4, 5]
题解
function flatArray(array) {
return array.reduce((acc, data) => {
return Array.isArray(data) ? acc.concat(flatArray(data)) : [...acc, data];
}, []);
}
console.log(flatArray([1, [1, 2, 3, [6, 7, 8, [10, 11, 12, 13]]], 4, 5]));