LoginSignup
0
0

More than 1 year has passed since last update.

【JavaScript】連想配列のキーを使ったソート

Posted at

連想配列のキーを使ったソートについてメモしておく。

連想配列のキーを使ったソート

連想配列のキーを使ったソートの前に、sort()を使った1次元配列の場合は以下となる。

const array = [10, 23, 50, 21, 45];
array.sort((a, b) => a - b);    // [ 10, 21, 23, 45, 50 ]

連想配列のキーを使ったソートも基本的には1次元配列の場合と変わらない。
オブジェクトのキーの値で降順ソートする場合のサンプルが以下となる。

const array = [
    { name: "ryota", score: 63 },
    { name: "taro", score: 85 },
    { name: "ken", score: 72 },
];
// 降順ソート
array.sort((a, b) => b.score - a.score);

// ソート後
 { name: 'taro', score: 85 },
 { name: 'ken', score: 72 },
 { name: 'ryota', score: 63 }

もし昇順にソートする場合は、b.score - a.scorea.score - b.scoreと書きかえればよい。
また、sort()破壊的メソッドであり、元の配列のデータを上書きしてしまうため、ソートを実行すると元の配列が得られなくなる。そのため、元の配列を残しておきたい場合は、あらかじめコピーしておく必要がある。配列のコピーはslice()が使える。

const array = [10, 23, 50, 21, 45];
const copy = array.slice();

array.sort((a, b) => a - b);    

console.log(array);    // [ 10, 21, 23, 45, 50 ]
console.log(copy);    // [ 10, 23, 50, 21, 45 ]
0
0
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
0
0