使用数组帮助程序函数的具有唯一值的数组



我正在使用ES6数组辅助函数reduce((find((。我正在尝试显示独特元素的数组。但在值为 0 的情况下它会失败。我无法找到我的代码有什么问题。请指导。

这是我的代码片段:

var arrayWithDuplicates = [0, 0, 1, 2, 3, 3, 4, 4, 'a', 'a'];
var arrayWithUniqueValues = arrayWithDuplicates
                            .reduce((previous, item) => {
                                if(!previous.find(element => element === item)) {
                                    previous.push(item)
                                }
                                return previous;
                            }, []);
console.log('arrayWithUniqueValues', arrayWithUniqueValues)

我得到以下输出:

arrayWithUniqueValues [ 0, 0, 1, 2, 3, 4, 'a' ]

为什么我得到两次 0 而所有其他值都是唯一的?

您可以通过将数组转换为 Set 并返回数组来获得相同的结果。

var arrayWithUniqueValues = [...new Set(arrayWithDuplicates)];

顺便说一下,你的代码不起作用的原因是Array.prototype.find返回它找到的元素。当您搜索 0 时,它返回 0,然后!0为 true。因此,即使它已经在数组中,也会添加 0。您可以改为:

if (previous.indexOf(item) === - 1) {
    previous.push(item);
}

find(( 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回未定义。

当你得到0时,代码变成:

arrayWithDuplicates.reduce(([0], 0) => {
                            if(!previous.find(element => element === item)) {
                            //![0].find(0=>0===0),return 0,so !0 means true
                                previous.push(item)
                            //so [0,0]
                            }
                            return previous;
                        });

更好的方法是

 let a=[...new Set([0, 0, 1, 2, 3, 3, 4, 4, 'a', 'a'])];//[0, 1, 2, 3, 4, "a"]

最新更新