LoginSignup
0
0

More than 1 year has passed since last update.

Javascript object の配列をあるメンバ変数を利用してソートしたい

Last updated at Posted at 2022-04-04

Javascript objectの配列をあるメンバ変数でソートする

たぶん今後自分が一番よく使う比較関数を利用するパタン

値を2つ受け取ってそれらの大小をjavascriptルールに従って判定して、大きければ1を小さければ-1を返すというのを作成

function compare(a,b) {
    let rtn_value = 0;
    if(a > b) {
        rtn_value = 1;
    } else if (b > a) {
        rtn_value = -1;
    }
    return rtn_value;
}

これを sort 関数の引数として渡してあげるとその評価関数にしたがってソートしてくれる

const array = [2, 4, 3, 8];
array.sort(compare);
// => 2, 3, 4, 8

これを応用する形でオブジェクトのメンバ変数を指定した比較関数を書いておく

objectのメンバ変数にdistanceという 'number'型の変数があったとします。

function compareMyObj(a,b) {
    let rtn_value = 0;
    if(a.distance > b.distance) {
        rtn_value = 1;
    } else if (b.distance > a.distance) {
        rtn_value = -1;
    }
    return rtn_value;
}

としておけば、distanceの大きさによってオブジェクトの配列がソートされるはずです。
実際にうまくいきました。

逆に大きい順に並べたいときには return する数値を反対にしてあげれば良さそうです。

function compareMyObj(a,b) {
    let rtn_value = 0;
    if(a.distance > b.distance) {
        rtn_value = -1;
    } else if (b.distance > a.distance) {
        rtn_value = 1;
    }
    return rtn_value;
}
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