拍平数组
递归实现
function flatten(arr: any): any[] {
if (!Array.isArray(arr)) {
return [arr];
}
let res: any[] = [];
arr.forEach((item) => {
flatten(item).forEach((item) => res.push(item));
});
return res;
}
console.log(flatten([1, [2, 3], [4, 5, [6, 7], 8], 9]));
console.log(flatten([1, [2, [3, ["a", [true], "b"], 4], 5], 6]));
堆实现
function flatten(arr: any[]) {
const res = [];
const stack = [arr];
while (stack.length) {
const item = stack.pop();
if (Array.isArray(item)) {
item.reverse().forEach((one) => stack.push(one));
} else {
res.push(item);
}
}
return res;
}
console.log(flatten([1, [2, 3], [4, 5, [6, 7], 8], 9]));
console.log(flatten([1, [2, [3, ["a", [true], "b"], 4], 5], 6]));