LoginSignup
2
2

More than 3 years have passed since last update.

【JavaScript】オブジェクトが格納されている配列で複数のキーでソート

Last updated at Posted at 2019-10-07

:book: こんな感じの配列があるとします

const items = [
  { id: "6", price: "340", name: "大根" },
  { id: "5", price: "230", name: "ポテト" },
  { id: "1", price: "100", name: "パセリ" },
  { id: "2", price: "340", name: "にんじん" }
]

:boom: 価格昇順でソートしたい場合

items.sort((a,b)=>a.price - b.price);

単純に価格昇順にしたいのであれば簡単で、これで実現出来ます。
ただし、これだけではpriceが同じものがあった場合idが昇順になってくれず

const items = [
  { id: "1", price: "100", name: "パセリ" },
  { id: "5", price: "230", name: "ポテト" },
  { id: "6", price: "340", name: "大根" },
  { id: "2", price: "340", name: "にんじん" }
]

こうなります。

:boom: 価格昇順でソート & 同じ価格ならid昇順 にしたいとする

つまりこうしたいです。

const items = [
  { id: "1", price: "100", name: "パセリ" },
  { id: "5", price: "230", name: "ポテト" },
  { id: "2", price: "340", name: "にんじん" },
  { id: "6", price: "340", name: "大根" }
]

:ok_hand: 実現方法

items.sort((a,b)=> {
  if(a.price > b.price) return 1
  if(a.price < b.price) return -1
  if(a.id > b.id) return 1
  if(a.id < b.id) return -1

  return 0;
});

このようにして実現出来ます。

もし2つではなく、3つ4つと比較したいキーが増えても条件分岐を増やして行けば良いです。

追記

コメントにて、@hayashi-ay さんより 1行で簡潔に書ける方法を教えて頂きましたので追記しておきます。

items.sort((a,b)=> (a.price - b.price) || (a.id - b.id) );
2
2
2

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
2
2