javascript配列の複数フィールドの並べ替え


マルチフィールドの並べ替えが必要な配列に対して、Javascriptのオリジナル配列apiを借りて完成します.
このアプリがsortの方法です.
arr.sort(sortby)
この方法のsortbyパラメータは任意であり,このパラメータは反転法である.
パラメータ:この方法には二つのパラメータがあります.この二つのパラメータは現在比較されている二つの要素です.
戻り値:0より大きい場合は、2つの値を交換します.そうでなければ、交換しません.
だから、私達はこのように書くことができます.
function sortNumber(a,b)
{
return a - b
}

var arr = new Array(6)
arr[0] = "10"
arr[1] = "5"
arr[2] = "40"
arr[3] = "25"
arr[4] = "1000"
arr[5] = "1"

document.write(arr + "
") document.write(arr.sort(sortNumber))
a-b>0の時、aとbは交換します.これは昇順です.
return a-bをreturn b-aと書くと降順です.
 
この基礎ができたら、多フィールドの並べ替えができます.
まず二つのフィールドの並べ替えの例を示します.
var jsonStudents = [
    {name:"Dawson", totalScore:"197", Chinese:"100",math:"97"},
    {name:"HanMeiMei", totalScore:"196",Chinese:"99", math:"97"},
    {name:"HanMeiMei", totalScore:"196",Chinese:"99", math:"10"},
    {name:"HanMeiMei", totalScore:"196",Chinese:"99", math:"80"},
    {name:"LiLei", totalScore:"185", Chinese:"88", math:"97"},
    {name:"XiaoMing", totalScore:"196", Chinese:"96",math:"100"},
    {name:"Jim", totalScore:"196", Chinese:"98",math:"98"},
    {name:"Joy", totalScore:"198", Chinese:"99",math:"99"}
];
    
jsonStudents.sort(function(a,b){
    if(a.totalScore === b.totalScore){
        return b.Chinese - a.Chinese;
    }
    return b.totalScore - a.totalScore;
});

console.log(jsonStudents);
もう一つの3つのフィールドの例を示します.
var jsonStudents = [
    {name:"Dawson", totalScore:"197", Chinese:"100",math:"97"},
    {name:"HanMeiMei", totalScore:"196",Chinese:"99", math:"97"},
    {name:"HanMeiMei", totalScore:"196",Chinese:"99", math:"10"},
    {name:"HanMeiMei", totalScore:"196",Chinese:"99", math:"80"},
    {name:"LiLei", totalScore:"185", Chinese:"88", math:"97"},
    {name:"XiaoMing", totalScore:"196", Chinese:"96",math:"100"},
    {name:"Jim", totalScore:"196", Chinese:"98",math:"98"},
    {name:"Joy", totalScore:"198", Chinese:"99",math:"99"}
];
    
jsonStudents.sort(function(a,b){
    if(a.totalScore === b.totalScore){
        if(b.Chinese === a.Chinese){
            return a.math - b.math;
        }
        return b.Chinese - a.Chinese;
    }
    return b.totalScore - a.totalScore;
});

console.log(jsonStudents);
仕上げ.