Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
TieMuZhen opened this issue Nov 13, 2021 · 0 comments
Open

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

TieMuZhen opened this issue Nov 13, 2021 · 0 comments

Comments

@TieMuZhen
Copy link
Owner

实现效果

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]]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant