Jump to content

Using the reduce() Function as a Frequency Counter


iwato

Recommended Posts

BACKGROUND:  Recently I discovered a nifty Javascript function that counts the like values of an index array and returns as its value an object whose property-value pairs consist of a single repeated value and its corresponding frequency.  Unfortunately, I am having trouble understanding how the function works.  As I have adapted it to fit my own needs I have changed the variable names.  Indeed, this change may be the source of my own confusion.

The FUNCTION:

function dateCounter(dates) {        
    return dates.reduce(
        (countDates, date) => {
                countDates[date] = ++countDates[date] || 1;
                return countDates;
            },
            {}
    );
}

REQUEST:  Please write in plain English what the so-called reducer function of the reduce( ) function is achieving with each iteration.  I am baffled.

Roddy

 

Link to comment
Share on other sites

It will return an array of the frequency of dates.  The line that sets countDates[date] is equivalent to this:

if (countDate[dates]) {
  countDate[dates] = countDate[dates] + 1;
}
else {
  countDate[dates] = 1;
}

 

  • Like 1
Link to comment
Share on other sites

OK.  you have adequately explained the following line of code.

countDates[date] = ++countDates[date] || 1;

Can you now explain this line of code.

(countDates, date) => {...; return countDates;},{})

The result set, by the way, appears to be an object of name-value pairs which is exactly what I was hoping for when I introduced the function into my code.

Object { 2019/01/01: 2, 2019/01/03: 4, 2019/01/04: 2, 2019/01/05: 2, 2019/01/06: 1, 2019/01/07: 2, 2019/01/09: 6, 2019/01/11: 1, 2019/01/18: 3, 2019/01/20: 2, 60 more… }

Roddy

Link to comment
Share on other sites

That's just a alternative way of defining a function in EcmaScript 6.  It's saying the function accepts 2 parameters, countDates and date, and then has the statements where it builds and then returns the array.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

The empty object is the initial value to use for the accumulator for reduce.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

  • Like 1
Link to comment
Share on other sites

So, why is it that the dateCounter() function only returns one name-value pair in a single object, if the initial empty object is left out?  The empty object appears to induce recursion, but I do not understand why.

Roddy

Edited by iwato
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...