Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using array.reduce method to count duplicate elements [duplicate]

I'm working through a tutorial on functional JS and I'm up to a challenge requiring the use of the reduce method:

Given a random array of words, output an array that shows the word plus it's word count, for instance: ['apple', 'orange', 'grape', 'apple'] -> ['apple: 2', 'orange: 1', 'grape: 1']

I know this isn't the correct use of reduce, but here was my semi-working solution:

var wordCountsArray = inputWords.map(function(item) {
    var counter = 0;
    var itemCount = inputWords.reduce(function(prevVal, curVal) {
        if (curVal == item) {
            counter++;
        }
        return;
    }, 0);

    return item + ": " + counter;
})

console.log(wordCountsArray);  

This did indeed output the word counts, but the word count list has duplicates, i.e. looks like:

['apple: 2', 'orange: 1', 'grape: 1', 'apple: 2']

instead of

['apple: 2', 'orange: 1', 'grape: 1']

I've looked up MSDN's guide on the method, Mozilla's, several blogs. I get how it works as an accumulator, but because it uses the output of the last iteration as input for the next, I have no idea how to apply it to this task. I don't need a solution, but maybe a little help in understanding?

like image 288
ZAR Avatar asked Dec 11 '22 05:12

ZAR


1 Answers

I know this is a solution, but sometimes solutions are the best explanations. Follow the "fruitsCount" object in the first block. Note that "fruitsArray" is simply a translation of this object, so that should be very easy to understand.

var fruits = ['apple', 'orange', 'grape', 'apple'].reduce(function(fruitsCount, currentFruit){
    if(typeof fruitsCount[currentFruit] !== "undefined"){
      fruitsCount[currentFruit]++; 
      return fruitsCount;
    } else {
        fruitsCount[currentFruit]=1; 
        return fruitsCount;
    }
}, {});

var fruitsArray = [];
for(var x in fruits){
    fruitsArray.push(x + ": " + fruits[x]);
}

console.log(fruitsArray);
like image 194
Monarch Wadia Avatar answered Dec 21 '22 22:12

Monarch Wadia