0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

オブジェクト配列の最小値と最大値を取得したい時はMath.min()とMath.max()

Posted at

はじめに

以下のようなオブジェクト配列があるとします。

const priceList = [
    {
        id: 1,
        price: 1300
    },
    {
        id: 2,
        price: 400
    },
    {
        id: 3,
        price: 100
    },
    {
        id: 4,
        price: 17200
    }
]

この時、priceの最小値と最大値を取得するにはどうしたらいいでしょうか?

解決策

1. sort()関数を使う
sort()で配列をソートしてからその先頭と末尾を取得する方法です。

const sortedPriceList = priceList.map((v) => v.price).sort((a, b) => {
    return a - b;
  });
  
const minPrice = sortedPriceList[0];
const maxPrice = sortedPriceList[sortedPriceList.length - 1];

2. Math.minMath.maxを使う

const minPrice = Math.min(...priceList.map(item => item.price));
const maxPrice = Math.max(...priceList.map(item => item.price));

Math.minMath.maxを使うと一瞬で最小値と最大値が取得できます!

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?