How to get min values among properties inside an array of objects?

Viewed 353

In React I have an object like:

shirt : {
title : "Abc",
material : "cotton",
options : [
    0 : {
    price: 10,
    color: red
    },
    1 : {
    price: 20,
    color: green
    },
    2 : {
    price: 30,
    color: blue
    },
}

In the catalog page I want to display only the cheapest option ("From $10") for every shirt.

To display all shirts I use map function:

shirts.map((shirt) => (<div>{shirt.title}</div><div>{shirt.material}</div>))

How can I show only the cheapest price?

I can not use {shirt.options.price[0]} because the first element of the array is not always the cheapest price.

1 Answers

You could do:

const minPrice = Math.min(...shirt.options.map(({price}) => price))
const cheapeastShirt = shirt.options.find({price} => minPrice === price)
Related