Home > Back-end >  Take an object from an array of objects based on the max value on one of its properties
Take an object from an array of objects based on the max value on one of its properties

Time:09-17

Let's say I got an array of object like this

const arr = [
  {name: 'John', age: 15},
  {name: 'Max', age: 17},
  {name: 'Tom', age: 11},
]

How can I take just the object containing Max, 17? This would be the result

b = [{ name: Max, age: 17 }]

or better

c = { name: Max, age: 17 }

CodePudding user response:

Reduce the array to the object with highest age:

const arr = [{"name":"John","age":15},{"name":"Max","age":17},{"name":"Tom","age":11}]

const result = arr.reduce((acc, o) => !acc || o.age > acc.age ? o : acc, null)

console.log(result)

I'm using null as the default value for the Array.reduce() to prevent an error if the array is empty. However, you can check for an empty array beforehand as well:

const findMaxAge = arr => arr.length 
  ? arr.reduce((acc, o) => o.age > acc.age ? o : acc)
  : null

const arr = [{"name":"John","age":15},{"name":"Max","age":17},{"name":"Tom","age":11}]

console.log(findMaxAge(arr))

console.log(findMaxAge([]))

CodePudding user response:

You can sort by age first, then the object with the highest age value will be at the start of the list:

const a = [
  {name: "John", age: 15},
  {name: "Max", age: 17},
  {name: "Tom", age: 11},
]

const sortedByAge = a.sort((a,b) => b.age - a.age);

const highestAge = sortedByAge[0];

console.log(highestAge);

CodePudding user response:

hope this code helping you

const a = [{name: 'John', age: 15},
       {name: 'Max', age: 17},
       {name: 'Tom', age: 11},];
const result = a.reduce((p, c) => p.age > c.age ? p : c);
console.log(result);

CodePudding user response:

Using the Array.prototype.reduce() is a clean way. this function iterates through the array one by one, at each step adding the current array value to the result from the previous step. in our case will compare the previous largest element to the current. the return value will be the object containing the largest value for the age key.

const arr = [
       {name: 'John', age: 15},
       {name: 'Max', age: 17},
       {name: 'Tom', age: 11},
    ]
    
const largest = arr.reduce((prev, current) => (prev.age > current.age) ? prev : current)

console.log(largest);

  • Related