Skip to content
Advertisement

How does this code work in context with reduce function?

It might be a very basic question for people here but I have to ask away. So I was going through reducce recently and I came through this example where I could find the maximum of some value in an array of object. Please, have a look at this code.

JavaScript

If I write soemthing like this to find the maximum years,

JavaScript

I get 22 as my value, and if I dont involve the property years, i.e-

JavaScript

I get the object Object {id: 2, name: “Temmin ‘Snap’ Wexley”, years: 30} as my value. Can someone explain why the first example is wrong and what is happening in there? Also, if I Just want to fetch the years value, how can I do that? Thanks in advance.

JavaScript

Advertisement

Answer

In the first example, as you are not returning the object there is no object property (years) of the accumulator (old) after the first iteration. Hence there is no year property to compare with.

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement