我正在处理ES6数组助手函数reduce()和find()。我正在尝试显示一系列独特的元素。但就价值资产管理公司( value )而言,它正在失败。我找不到我的代码出了什么问题。请指点。
下面是我的代码片段:
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两次呢?
发布于 2018-01-21 12:08:30
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"]发布于 2018-01-21 12:03:23
通过将数组转换为集合并返回到Array,可以实现相同的结果。
var arrayWithUniqueValues = [...new Set(arrayWithDuplicates)];顺便说一句,您的代码不能工作的原因是Array.prototype.find返回它找到的元素。搜索0时,它返回0,然后!0为true。因此,即使它已经在数组中,也会添加0。你可以做的是:
if (previous.indexOf(item) === - 1) {
previous.push(item);
}https://stackoverflow.com/questions/48366417
复制相似问题