LoginSignup
33
35

More than 5 years have passed since last update.

JavaScript 連想配列の任意のキーでのソート方法

Last updated at Posted at 2016-08-02

固定のキー

// ソート対象のデータ
let users = [
    {id: 1, name: "ジャック", birthdate: "1996/10/01", age: 20},
    {id: 2, name: "ジョン", birthdate: "1990/05/05", age: 26},
    {id: 3, name: "ボブ", birthdate: "1996/11/14", age: 20},
    {id: 4, name: "マイケル", birthdate: "1995/10/01", age: 21},
    {id: 5, name: "アルバート", birthdate: "1984/09/10", age: 32},
    {id: 6, name: "メアリー", birthdate: "1994/07/22", age: 22},
    {id: 7, name: "ジョン", birthdate: "1997/08/02", age: 19},
    {id: 8, name: "フランク", birthdate: "1990/09/10", age: 26},
    {id: 9, name: "ボブ", birthdate: "1988/08/02", age: 28},
    {id: 10, name: "ダニエル", birthdate: "1994/04/02", age: 22}
];

// age, idの順にソート(昇順)
users.sort((a, b) => {
    if (a.age < b.age) return -1;
    if (a.age > b.age) return 1;
    if (a.id < b.id) return -1;
    if (a.id > b.id) return 1;
    return 0;
});

任意のキー

// ソート対象のデータ
let users = [
    {id: 1, name: "ジャック", birthdate: "1996/10/01", age: 20},
    {id: 2, name: "ジョン", birthdate: "1990/05/05", age: 26},
    {id: 3, name: "ボブ", birthdate: "1996/11/14", age: 20},
    {id: 4, name: "マイケル", birthdate: "1995/10/01", age: 21},
    {id: 5, name: "アルバート", birthdate: "1984/09/10", age: 32},
    {id: 6, name: "メアリー", birthdate: "1994/07/22", age: 22},
    {id: 7, name: "ジョン", birthdate: "1997/08/02", age: 19},
    {id: 8, name: "フランク", birthdate: "1990/09/10", age: 26},
    {id: 9, name: "ボブ", birthdate: "1988/08/02", age: 28},
    {id: 10, name: "ダニエル", birthdate: "1994/04/02", age: 22}
];

// ソートの優先するキーと順序のリスト
// age, name, idの順にソート
const order = [
    {key: "age", reverse: false},
    {key: "name", reverse: false},
    {key: "id", reverse: false}
];

// ソート関数(デフォルトで昇順)
function sort_by(list) {
    return (a, b) => {
        for (let i=0; i<list.length; i++) {
            const order_by = list[i].reverse ? 1 : -1;
            if (a[list[i].key] < b[list[i].key]) return order_by;
            if (a[list[i].key] > b[list[i].key]) return order_by * -1;
        }
        return 0;
    };
}

// ソート
users.sort(sort_by(order));

ソート用の関数に{key: "ソート対象のキー", reverse: false}形式のオブジェクトのリストを渡すことでそのキーを基準にソートする。
リストの前の方が優先度が高い、reverse: falseが昇順でtrueに変えると降順になる。

33
35
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
33
35