Help us understand the problem. What is going on with this article?

【JavaScript】連想配列の値(value)で並び替え

連想配列の値で並び替えをしてみた。

以下のような連想配列を値が大きい順にソートしたかったので、挑戦してみました。

let obj = {
  "Apple" : 10,
  "Orange" : 5,
  "Banana" : 12,
  "Mango" : 2,
  "Melon" : 7,
}

キーと値にそれぞれキーをつけた連想配列を格納した配列の作成

let arr = let arr = Object.keys(obj).map((e)=>({ key: e, value: obj[e] }));
console.log(arr);

// [ { key: 'Apple', value: 10 },
//   { key: 'Orange', value: 5 },
//   { key: 'Banana', value: 12 },
//   { key: 'Mango', value: 2 },
//   { key: 'Melon', value: 7 } ]

※mapに訂正しました。

キー[value]でソート

上記で作成した連想配列を格納した配列をキー[value]でソートします。

arr.sort(function(a,b){
  if(a.value < b.value) return 1;
  if(a.value > b.value) return -1;
  return 0;
});
console.log(arr);

// [ { key: 'Banana', value: 12 },
//   { key: 'Apple', value: 10 },
//   { key: 'Melon', value: 7 },
//   { key: 'Orange', value: 5 },
//   { key: 'Mango', value: 2 } ]

いぇーい(^^)
すごく回りくどいけどソートすることができました!

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした