Categories
JavaScript Answers

How to compare JavaScript array of objects to get min / max?

Spread the love

To compare JavaScript array of objects to get min / max, we call the Math.min and Math.max methods.

For instance, we 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));

to call myArray.map to get the cost property values in an array.

Then we spread the values as arguments of Math.min and Math.max to get the min and max values.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published.