Reduce Method - example

I don’t know what’s happening here, more specifically, I was able to follow everything until now, but since prototypes etc it has been a real struggle and I have no idea if I can actually wrap my head around this concepts and more than anything else apply them to the creation of a webpage, since so far it has been a ton of theory with zero practise on the real thing.

Anyway, now, I’m not even doing the exercise, I don’t uderstand the example. This is an arrow function, right?
Ok, where does obj come from? reduce is called on users (users.reduce), how do we know obj refers to users? In the lesson it was written that the callback function of reduce accepts 4 arguments, and that for this example only two were going to be used, the first being the accumulator (so the result of the last return of the callback function) and the second which is the current element being processed…well, it doesn’t look like that in the function to me, how’s obj and user the elements being processed in that order? And ultimately, where does the final , {}); come from?

I’m starting to think that I’m really dumb because this doesn’t make any sense to me…if anyonw could dumb down this for me maybe I’ll be able to understand what’s going on


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);
  **Your browser information:**

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

Challenge: Use the reduce Method to Analyze Data

Link to the challenge:

reduce() is array method, that can do a lot of stuff, very handy method, and it has few arguments it needs to do what needs to be done, for instance, obj is referencing to ‘array’ in question and rest of its arguments are optional, you can learn more about it from here

Yeah, you’re not dumb, the reducer is a bit confusing, kinda like when first introducted to recursive algorithms.

Basically, reducer is an array function, that uses the callback function to go through each item in your array, and accumulate the data into a result… At a minimum the callback function needs the accumulated value, and the array object… but can also include array index and the array itself if you need to access the array directly during your analysis. When the method first runs, you can assign a value to accumulated value at the beginning… that’s what the ‘{}’ is in your example. The return value for the function is the final value of the accumulated value.

Array.reducer( (accumulated value, array item) => { some function }, original value for 'accumulated value')

So it may help to look at a simple example… lets say you want to add the value of all your home items:

 myHomeItems =    [{name: 'tv', value: 1000}
                   {name: 'couch', value: 500},
                   {name: 'toaster', value: 30}]

You could sum those up with a for loop, but can also use the reducer. Basically we will use reducer to accumulate the sum of all the items:

total = myHomeItems.reduce( (theSum, theItem) => { theSum + theItem.value } , 0)

So, the 0 on the end is the original value you want to start theSum with…then the callback function runs for each item in the array, and each time, theSum for the next function ends up being the return value of the previous function. So if we step through the callback:

 (0, tvObject) =>  returns 0 + 1000     
(1000, couchObject) => returns 1000 + 500
(1500, toasterObject) => returns 1500 + 30

Final return value would be 1530, and thats what total would equal. This can be used to build a new array, or a new objectject, add values, or do a lot of things.

In your example obj is like theSum… its what you’re building, and its starting value is ‘{}’ . So as it runs, it checks each ‘user’, and adds to the current object the key of username, and a value of age… stepthrough would look like this.

({}, johnobject) => return {John: 34}
({John: 34}, amyobject) => return {John: 34, Amy: 20}
({John:34, Amy:20}, catobject) => return {John: 34, Amy: 20, camperCat: 10}

Final return value is the object: {John: 34, Amy: 20, camperCat: 10}

Hope that clears it up a bit.

3 Likes

The JS part is pretty much all about handling logic and not directly related to web-design. What you learn there, you can apply to any branch of programming. It is certainly very handy for webdev and once you move on to frontend libraries, you will see the power of enhancing your web pages with logical code.
It is totally normal to feel overwhelmed, as the JS curriculum is filled with lot of things to learn and each one depends on the previous, or several previous stuff and loosing thread is easy. It also takes time and practice, using those stuff, so dont expect you would learn all ofthem at once; it definitely takes long time and patience and you might return to some stuff over and over for months to come.
Reduce is quite complex method to learn and work with and it involves other notions, like callbacks, how methods work, often you will see it paired with destructuring and other more contemporary syntaxis, so not being very familiar with either of those, can make it real hard to get reduce.
Others have laid good explanations on the method, ill add my own description as well, as i believe often, having seen the same thing explained few times differently, can help you actually grasp it.
To understand how something works, often helps to know what purpose it serves. Reduce mean is to go over an array of elements and working with those elements, derive a value, often quite different from the array you started with. E.g. you start with an array, you get a string, you start with an array, you get an object, or a number, pretty much whatever you need to build for your needs, related to the array data you work with. Reduce can achieve the result of several other, lesser methods attached, like map/filter etc. That value you return at the end, you start building from the start. It is passsed over and over, for every element, as the first argument(named obj in the particular case). You can assign an explicit starting value for it(usually useful when you want to return totally different item from the array itself), by passing a second argument to reduce. In the current case, that second argument is {}. The format looks like this

array.reduce(callback, initialValue)
// initialvalue often refered to as accumulator

You can also omit passing an initial value for the accumulator and as such, the first element in the array will be used. In your code you use as callback an arrow function, defined on the spot. You always want to return something in the callback, which is that accumulator, we pass between calling the callback with every element, to accumulate the final value we are to return from reduce.

A lot of good explanations here, I will just add that the prototype methods can be confusing for learners and reduce especially can be confusing. I’ve even run into experienced mid-level devs that still didn’t quite understand reduce. But it’s also really powerful and cool, once you get it.

Thanks guys, yesterday I felt really stressed and decided I had to take a break, that’s why I’m replying only now. Yeah, it’s definitely a lot of stuff, now I’ll carefully read everything and write it down on my notebook

I’ve made it, I’m so happy, created my own solution and it works! Ahhh, I’m very pleased with myself, thanks guys!

function getRating(watchList) {
  // Only change code below this line
  let directedMovies = 0;
  const averageRating = watchList.reduce(function(accumulator, current) {
    if (current["Director"] == "Christopher Nolan") {
        directedMovies += 1;
        return  accumulator + (Number(current["imdbRating"]));
        }
     return accumulator / directedMovies;
     }, 0);
  // Only change code above this line
  return averageRating;
}

console.log(getRating(watchList));
1 Like

Cool, good job.

Since it is a working solution to curriculum, I’ve added [spoiler][/spoiler] tags.

Oh sure, thanks, sorry I didn’t know that!

That’s cool. We all have to find out some way.

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