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.

var pilots = [
    {
        id: 10,
        name: "Poe Dameron",
        years: 14
    }, {
        id: 2,
        name: "Temmin 'Snap' Wexley",
        years: 30
    }, {
        id: 41,
        name: "Tallissan Lintra",
        years: 16
    }, {
        id: 99,
        name: "Ello Asty",
        years: 22
    }
];

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

var oldest_of_them_all = pilots.reduce(function (old, current) {
    var old = (old.years > current.years) ? old.years : current.years;
    return old
})

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

var oldest_of_them_all = pilots.reduce(function (old, current) {
    var old = (old.years > current.years) ? old : current;
    return old
})

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.

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.

var pilots = [
    {
        id: 10,
        name: "Poe Dameron",
        years: 14
    }, {
        id: 2,
        name: "Temmin 'Snap' Wexley",
        years: 30
    }, {
        id: 41,
        name: "Tallissan Lintra",
        years: 16
    }, {
        id: 99,
        name: "Ello Asty",
        years: 22
    }
];

var oldest_of_them_all = pilots.reduce(function (old, current) {
  console.log(old);// the value is not the object having the property years after the first iteration
  var old = (old.years > current.years) ? old.years : current.years;
  return old;
})
console.log(oldest_of_them_all);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement