Categories
JavaScript Answers

How to Get Min or Max Value of a Property in a JavaScript Array of Objects?

Spread the love

We can get the min or max value of a property in objects in a JavaScript object array by calling map to create an array of the property values.

Then we can use the Math.min or Math.max methods to get the min or max values from the array by spreading the value array as arguments into the methods.

For instance, we can write:

const myArray = [{
  id: 1,
  cost: 200
}, {
  id: 2,
  cost: 1000
}, {
  id: 3,
  cost: 50
}, {
  id: 4,
  cost: 500
}]
const min = Math.min(...myArray.map(item => item.cost))
const max = Math.max(...myArray.map(item => item.cost));

console.log(min);
console.log(max);

to get the min and max value of the cost property in myArray .

We call myArray.map to create an array with the cost property value in each object in the array.

Then we spread the values as arguments into Math.min or Math.max to get the min and value of the cost property respectively.

Therefore, min is 50 and max is 1000.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *