Functional Programming - Use the reduce Method to Analyze Data

hello,

Could you plz explain what obj is here and what is its role in the code?

``````const users = [
{ name: 'John', age: 34 },
{ name: 'Amy', age: 20 },
{ name: 'camperCat', age: 10 }
];

const usersObj = users.reduce((obj, user) => {
obj[user.name] = user.age;
return obj;
}, {});
console.log(usersObj);
``````

WARNING

The challenge seed code and/or your solution exceeded the maximum length we can port over from the challenge.

You will need to take an additional step here so the code you wrote presents in an easy to read format.

Please copy/paste all the editor code showing in the challenge from where you just linked.

``````Replace these two sentences with your copied code.
Please leave the ``` line above and the ``` line below,
because they allow your code to properly format in the post.
``````

User Agent is: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36`

Challenge: Functional Programming - Use the reduce Method to Analyze Data

Reduce accepts two params, in this case they are called â€śobjâ€ť and â€śuserâ€ť. Sometime they are called â€śaccumulatorâ€ť and â€ścurrentâ€ť or â€śaccâ€ť and â€ścurâ€ť or even â€śaâ€ť and â€ścâ€ť. The first param â€śaccumulatesâ€ť the data. It is what the previous iteration returned. The second is the â€ścurrentâ€ť element from the array.

So, if you have:

``````[1, 3, 5, 10].reduce((acc, cur) => acc + cur, 0)
// 19
``````

we are telling reduce to start with `0`. So, on the first iteration, acc is `0` and the cur is `1`. It add those together and returns that. That becomes the acc on the next iteration. So, on the second iteration acc is `1` and cur is `3`. We add those together and return `4`. That becomes the acc on the next iteration. So on the next iteration acc is `4` and cur is `5`â€¦

We continue doing that until we get our total sum.

Are â€śaccâ€ť and â€ścurâ€ť good names? Could we do something more specific:

``````[1, 3, 5, 10].reduce(
(runningTotal, currentNumber) => runningTotal + currentNumber,
0,
)
// 19
``````

That might be more clear. I donâ€™t know, I might use â€śaccâ€ť and â€ścurâ€ť for simple ones like this, but if things get confusing, good variable name can make a huge difference.

In the code you show, they called them â€śobjâ€ť and â€śuserâ€ť. â€śobjâ€ť is the accumulator, it is an object to which you are adding each user. â€śuserâ€ť makes sense for the current element - thatâ€™s what it is.

1 Like

Thank you so much. That was comprehensive and helpful.

1 Like

reduce is a hard method to wrap your head around. Seriously, Iâ€™ve had to explain it to a mid-level dev. But itâ€™s also very powerful.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.