13
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2019-02-26

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

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

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

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

```JavaScript 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 } ]

<p>※mapに訂正しました。</p>

<h3>キー[value]でソート</h3>
<p>上記で作成した連想配列を格納した配列をキー[value]でソートします。</p>
```JavaScript
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 } ]

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

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?