LoginSignup
2
1

More than 3 years have passed since last update.

連想配列を指定した順番に並び替える

Last updated at Posted at 2020-06-29

名前順でも日付順でもなくてこの順番でソートしたい!
って時やりかたわかんなくてちょっと困っちゃったので忘備録。

例えば、干支。

const HogeItem = [
  { eto: '', ...hogehoge },
  { eto: '', ...hogehoge },
  { eto: '', ...hogehoge },
  { eto: '', ...hogehoge },
  { eto: '', ...hogehoge },
];

のような連想配列があって、これを干支順に並び替えたいと。
以下のコードで解決です。

const etoIndex = ['', '', '', '', ''];
HogeItem.sort((a, b) =>
  etoIndex.indexOf(a.eto) - etoIndex.indexOf(b.eto),
);

sort()は1か-1を返す使い方しか知りませんでした!

参考:Array.prototype.sort() - JavaScript | MDN

2
1
0

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
1