Open
Description
实现效果
flattenDeep([1, [2, [3, [4]], 5]]); // [1, 2, 3, 4, 5]
实现方法
利用 Array.prototype.flat
ES6 为数组实例新增了flat
方法,用于将嵌套的数组变成一维数组。该方法返回一个新数组
,对原数组没有影响。
flat
默认只会 “拉平” 一层,如果想要 “拉平” 多层的嵌套数组,需要给flat
传递想要拉平的层数。
/**
* deepLength 想要拉平的层数
*/
function flattenDeep(arr, deepLength) {
return arr.flat(deepLength);
}
console.log(flattenDeep([1, [2, [3, [4]], 5]], 3));
当传递的整数大于
数组嵌套的层数时,会将数组拉平为一维数组,JS能表示的最大数字为Math.pow(2, 53) - 1
,因此我们可以这样定义 flattenDeep 函数
function flattenDeep(arr) {
// 大多时候我们不会嵌套这么多层级
return arr.flat(Math.pow(2,53) - 1);
}
console.log(flattenDeep([1, [2, [3, [4]], 5]]));
利用 reduce、concat和递归实现
function flattenDeep(arr){
return arr.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
}
console.log(flattenDeep([1, [2, [3, [4]], 5]]));