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.

Your browser information:

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

Link to the challenge:

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.