我试图遍历一个包含多个数字的数组,并返回一个包含所有这些数字但不重复的数组。我必须使用 JavaScript 的 reduce
和 find
方法。我该怎么做?
我尝试过这个:
var numbers = [1, 1, 2, 3, 4, 4];
function unique(numbers) {
var result = numbers.reduce(function(resultsArray, number) {
resultsArray.find(function(numberInResultsArray) {
if (numberInResultsArray === number) {
return true;
}
});
}, []);
return result;
}
unique(numbers);
...但它给了我一个 TypeError
:
TypeError: Cannot read property 'find' of undefined
看来我的数组没有定义,但我不明白为什么它不会。有什么建议吗?
最佳答案
reduce callback的返回值将成为下一个调用/步骤中 resultsArray
的值。由于您的回调没有 return 语句,因此第二次调用回调时,最初的空数组 []
将变为 undefined
。
如果您想将数组减少为其唯一值,我建议使用以下方法:
function unique(numbers) {
return [...new Set(numbers)];
}
// Example:
console.log(unique([1, 1, 2, 3, 4, 4]));
只要数组值是或可以映射到primitives,这种方法就有效。 。 number
是一种原始类型。
如果您无法避免或坚持使用 reduce
和 find
,请使用例如:
function unique(numbers) {
return numbers.reduce((unique, next) => {
if (!unique.find(n => n === next)) unique.push(next);
return unique;
}, []);
}
// Example:
console.log(unique([1, 1, 2, 3, 4, 4]));
与 Set
方法使用的线性时间相比,该解决方案的完成时间为二次方。
关于javascript - reduce() 和 find() 抛出 TypeError - 无法读取未定义的属性 'find',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44077794/