gpt4 book ai didi

javascript - 在reduce()中跳过嵌套数组中的空数组

转载 作者:行者123 更新时间:2023-12-02 22:13:41 27 4
gpt4 key购买 nike

我嵌套了数组(父数组中的数组)。

let myArray = [ [], [ 8300, 8400, 8500, 8600 ], [ 6379 ], [ 5672 ], [ 27017 ] ]

我正在尝试将所有这些混合到一个数组中。

let targetArray = [8300, 8400, 8500, 8600, ..., 27017]

我使用reduce和concat来实现这个目标。

let unique_array = myArray.map(p=>{p}).reduce((prev, next)=>{prev && prev.concat(next))

但我收到此错误:

Uncaught Error TypeError: Reduce of empty array with no initial value

所以我的问题是如何跳过这个错误?

最佳答案

为什么不Array.prototype.flat() :

The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

let myArray = [ [], [ 8300, 8400, 8500, 8600 ], [ 6379 ], [ 5672 ], [ 27017 ] ];

let targetArray = myArray.flat();

console.log(targetArray);

关于javascript - 在reduce()中跳过嵌套数组中的空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59466618/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com