How to retrieve the values in the array after comparison

Viewed 29

Here is my JavaScript:

let test = [
  {
    name : 'doe',
    age : 8
  },
  {
    name : 'john',
    age : 17
  }
],
console.log(test.reduce((acc, curr) => curr.age > acc ? curr.age : acc, 0))

I did a comparison with age, but I want the result to be a name (John). if I console curr.name the result is doe. How could I do this?

1 Answers

You can store the entire object in the accumulator and use destructuring assignment.

let test = [
  {
    name : 'doe',
    age : 8
  },
  {
    name : 'john',
    age : 17
  }
];
let {name} = test.reduce((acc, curr) => curr.age > acc.age ? curr : acc, {age: 0});
console.log(name);

Related