对于需要多字段排序的数组,我们可以借用javascript的原生数组api来完成,
这个方法的sortby参数可选,这个参数是一个回调方法。
参数:该方法有两个参数,这两个参数是当前比较的两个元素。
返回值:大于0时将两个值互换,否则不换。
所以,我们就可以这样来写:
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);
再来一个三个字段的例子:
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);
收工。