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;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…