JavaScript 从浅入深 100 题训练计划--(4)扁平化数组
// 输入
[1, [2, [3, [4, 5]]]]
// 输出
[1, 2, 3, 4, 5]
const arr = [1, 2, 4, [5, 6, [7, 8]]]
function flatCustom(arr) {
let list = [];
let len = arr.length;
for (let i = 0; i < len; i++) {
if (Array.isArray(arr[i])) {
list = list.concat(flatCustom(arr[i]))
} else {
list.push(arr[i])
}
}
return list;
}
function flatC(arr) {
let stack = [...arr]
let list = []
while (stack.length) {
const item = stack.pop()
if (Array.isArray(item)) {
stack.push(...item)
} else {
list.push(item)
}
}
return list.reverse();
}
function flatReduce(arr) {
return arr.reduce((acc, cur) =>
acc.concat(Array.isArray(cur) ? flatReduce(cur) : cur)
, [])
}
function flattenDepth(arr, depth = 1) {
if (depth === 0) return arr.slice();
return arr.reduce((acc, cur) => {
if (Array.isArray(cur) && depth > 0) {
return acc.concat(flattenDepth(cur, depth - 1));
}
return acc.concat([cur]);
}, []);
}
console.log(flattenDepth(arr, 1)); // [1, 2, [3, [4]]]
console.log(flattenDepth(arr, 2)); // [1, 2, 3, [4]]
console.log(flattenDepth(arr, Infinity)); // [1, 2, 3, 4]
console.log(flatCustom(arr), 'flat', flatC(arr), arr.flat(Infinity), flatReduce(arr))
console.log(flatCustom(arr), 'flat', flatC(arr), arr.flat(Infinity), flatReduce(arr))

浙公网安备 33010602011771号