问题
var atLeast = function (tab,n,k){
var frequencyK = tab.reduce(function (acc, val, array){
if (val == k){
return acc+1;
}
});
return frequencyK >= n;
};
console.log(atLeast([1,2,3,2,2,4,2,2],4,2));
This function is meant to return true if the argument k is repeated in the array tab at least n times. To do this I used reduce, and incremented the accumulator by 1 each time that the current value was equal to k. I then I compared the frequency of k calculated with the reduce function with n.
The problem is that frequencyK ends up being NaN. I can't figure out why that is.
回答1:
Reduce takes two arguments, the reduction function and the initial value, you dropped the initial value, and thus it starts with the first element, which is the wrong number.
Additionally, when you return nothing, the next acc
gets a value of undefined
, which won't do at all in a math operation (this gets you the NaN).
To correct this, add 0
as an initial value to .reduce()
, and return in all cases, like so:
var atLeast = function (tab,n,k){
var frequencyK = tab.reduce(function (acc, val, array){
if (val == k){
return acc+1;
}
return acc;
}, 0);
return frequencyK >= n;
};
console.log(atLeast([1,2,3,2,2,4,2,2],4,2));
However, I think the following is a simpler way:
const atLeast = (tab, n, k) => tab.filter(item => item === k).length >= n;
回答2:
You need to return for all cases in the reduce function.
var atLeast = function (tab,n,k){
var frequencyK = tab.reduce(function (acc, val, array){
return val == k ? acc+1 : acc; //return the val for both cases
}, 0); //<-- set zero here
return frequencyK >= n;
};
console.log(atLeast([1,2,3,2,2,4,2,2],4,2));
来源:https://stackoverflow.com/questions/41230992/function-using-reduce-not-working-returning-false-when-should-be-true