Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...