Need Help Understanding .reduce (More Intricately)

Hey all, I’m practicing functional programming to pass job technical Interviews. This type of coding is relatively new to me and I need some help understanding some things.

This question is a warmup challenge on HackerRank here ->

So… I understand .reduce() pretty well and I’ve found a solid answer to this HackerRank question but I need help interpreting whats actually going on. I don’t want to move on with my practice without understanding this :). Thanks!

My answer to the HackerRank challenge ->

function equalizeArray(arr) {
    let countArr = Object.values(
    arr.reduce((accumulator, currentValue) => {
      accumulator[currentValue] = !accumulator[currentValue] ? 1 : accumulator[currentValue] + 1;
        return accumulator;
    }, {})
    );
    
    return arr.length - Math.max(...countArr);
    
}

What is your solid answer? Can you post your code?

Sorry about that. I thought it would show. I’ve edited it into the post :slight_smile:

I will focus on the arr.reduce portion (shown below):

    arr.reduce((accumulator, currentValue) => {
      accumulator[currentValue] = !accumulator[currentValue] ? 1 : accumulator[currentValue] + 1;
        return accumulator;
    }, {})

The first argument (the accumulator) starts as an empty object, because the the 2nd parameter of the reduce method is {} (see highlight below).

Inside the callback function a property (represented by currentValue) will be assigned a value based on the ternary operator expression. In this case, if there is no existing property represented by currentValue, then the value 1 will be assigned to this property. Otherwise, the current value of this same property will be incremented by 1. The return accumulator; line is needed so at the start of the next iteration, accumulator will start with an object containing the properties/values of the previous iteration.

1 Like

After a nights rest this makes a lot of sense. I was definitely over analyzing a bit. Thanks for the quick response and thorough answer Randell.