Question

I am attempting to go through an array and add up all the numbers. I used console.log to show me what values the script was using as shown below. I keep trying different variations of things in the if() but nothing seems to be working properly.

    var billycount = 0;
    var billyTotalScore = billyScoreList.reduce(function(score, total) {
        if(score === " ") {
        billycount += 1;
        }
        return +total + +score; 
    });
    console.log(billycount); //0
    console.log(billyTotalScore); //30
    console.log(billyScoreList); // ["12", " ", "18"]
    console.log(billyAverageScore) //10

    var billyAverageScore = billyTotalScore/(billyteamlist.length - billycount);

The answer to billyAverageScore should equal 15 (30/2).

I tried if(score === "0") which gives me the same answers as above and if (score !== true) which gives me a count of 2 and an average of 30. I think reduce() is treating the empty string as a 0. I want to be able to count all the empty strings so I can discount them from the length when finding the average.

I have been wrestling this forever and feel like I'm missing one key concept behind it. Any help would be great! Thanks!

UPDATE:

For anyone who stumbles across this, here is the code I got to work.

var billycount = 0;
    var billyTotalScore = billyScoreList.reduce(function(total, score) {
        if (score === " " || total === " ") {
        billycount++;   
        }
        return +total + +score; 
    });

    var billyAverageScore = billyTotalScore/(billyteamlist.length - billycount);

When I was just checking if (score === " ") I was forgetting that score will never be equal to the first term in the array. I just added || total === " ". the only time this would break down would be if the first element was " " and the second element was 0. I would want to billycount++ for the first element but not for the second. I'll have to give that some more thought.

Was it helpful?

Solution

The callback function of reduce should be function(total, score) instead of function(score, total).

see MDN:

previousValue
    The value previously returned in the last invocation of the callback, or initialValue, if supplied. (See below.)
currentValue
    The current element being processed in the array.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top