数组扁平化
简易一、使用扩展运算符实现一层扁平
function flat(array){
return [].concat(...array);
}
const array = [1,[2,3,[4,5,6,[7,8,9,[10,11,12,13,14]]]]]
const result = flat(array);
console.log(result); // [ 1, 2, 3, [ 4, 5, 6, [ 7, 8, 9, [Array] ] ] ]
简易二、使用 reduce
与 concat
实现一层扁平
function flat(array){
return array.reduce((accumulator,currentValue)=>{
return accumulator.concat(currentValue)
},[])
}
const array = [1,[2,3,[4,5,6,[7,8,9,[10,11,12,13,14]]]]]
const result = flat(array);
console.log(result); // [ 1, 2, 3, [ 4, 5, 6, [ 7, 8, 9, [Array] ] ] ]
方案一、使用数组API flat
const array = [1, [2, 3, [4, 5, 6, [7, 8, 9, [10, 11, 12, 13, 14]]]]];
const result = array.flat(2)
console.log(result);
方案二、使用 reduce
+ concat
递归实现深层扁平
完整写法
function flat(array, deep = 1) {
if (deep > 0) {
return array.reduce((accumulator, currentValue) => {
if (!Array.isArray(currentValue)) {
return accumulator.concat(currentValue);
} else {
return accumulator.concat(flat(currentValue, --deep));
}
}, []);
} else {
return array.slice();
}
}
const array = [1, [2, 3, [4, 5, 6, [7, 8, 9, [10, 11, 12, 13, 14]]]]];
const result = flat(array, 2);
console.log(result); // 结果: [ 1, 2, 3, 4, 5, 6, [ 7, 8, 9, [ 10, 11, 12, 13, 14 ] ] ]
优雅简洁写法
function flat(array, deep = 1) {
return deep > 0
? array.reduce(
(accumulator, currentValue) =>
accumulator.concat(
Array.isArray(currentValue)
? flat(currentValue, --deep)
: currentValue
),
[]
)
: array.slice();
}
const array = [1, [2, 3, [4, 5, 6, [7, 8, 9, [10, 11, 12, 13, 14]]]]];
const result = flat(array, 2);
console.log(result); // 结果: [ 1, 2, 3, 4, 5, 6, [ 7, 8, 9, [ 10, 11, 12, 13, 14 ] ] ]
方案三、使用 forEach
+ push
递归实现深层扁平
function flat(array, deep = 1) {
const result = [];
const recurse = function(currentArray,currentDeep){
currentArray.forEach((currentValue)=>{
if(Array.isArray(currentValue) && currentDeep>0){
recurse(currentValue,--currentDeep)
}else{
result.push(currentValue)
}
})
}
recurse(array,deep);
return result;
}
const array = [1, [2, 3, [4, 5, 6, [7, 8, 9, [10, 11, 12, 13, 14]]]]];
const result = flat(array, 2);
console.log(result); // 结果: [ 1, 2, 3, 4, 5, 6, [ 7, 8, 9, [ 10, 11, 12, 13, 14 ] ] ]
方案四、使用堆栈 循环迭代实现深层扁平
function flat(array) {
const stack = [...array];
const result = [];
while (stack.length) {
const currentValue = stack.shift();
if (Array.isArray(currentValue)) {
stack.unshift(...currentValue);
} else {
result.push(currentValue);
}
}
return result;
}
const array = [1, [2, 3, [4, 5, 6, [7, 8, 9, [10, 11, 12, 13, 14]]]]];
const result = flat(array);
console.log(result); // 结果: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]
方案五、使用Generator
循环迭代实现深层扁平
function* flat(array) {
for (let item of array) {
if (Array.isArray(item)) {
yield* flat(item);
} else {
yield item;
}
}
}
const array = [1, [2, 3, [4, 5, 6, [7, 8, 9, [10, 11, 12, 13, 14]]]]];
const result = [...flat(array)];
console.log(result); // 结果: // 结果: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]