Skip to content

将嵌套的数组扁平化处理 #3

Open
@TieMuZhen

Description

@TieMuZhen

实现效果

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]]));

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions