Languages
[Edit]
EN

JavaScript - compare array of objects to get min / max

0 points
Created by:
Eshaal-Wilkinson
774

In this article, we would like to show you how to compare an array of objects to get the min/max value of a property in JavaScript.

1. Minimum

In this example, we use reduce() method with ternary operator (?) to get an object with a minimum number property value from array of objects.

// ONLINE-RUNNER:browser;

var array = [
    { id: 1, number: 20 },
    { id: 2, number: 30 },
    { id: 3, number: 10 }
];

var min = array.reduce(function(previous, current) {
    return previous.number < current.number ? previous : current;
});

console.log(JSON.stringify(min)); // {"id":3,"number":10}

2. Maximum

In this example, we use reduce() method with ternary operator (?) to get an object with a maximum number property value from array of objects.

// ONLINE-RUNNER:browser;

var array = [
    { id: 1, number: 20 },
    { id: 2, number: 30 },
    { id: 3, number: 10 }
];

var max = array.reduce(function(previous, current) {
    return previous.number > current.number ? previous : current;
});

console.log(JSON.stringify(max)); // {"id":2,"number":30}

 

References

  1. Array.prototype.reduce() - JavaScript | MDN
  2. Conditional (ternary) operator - JavaScript | MDN

Alternative titles

  1. JavaScript - find min / max property value in array of objects
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join