Function using reduce not working; returning false when should be true

只谈情不闲聊 提交于 2019-12-13 09:22:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!