一、排序
1.根據(jù)對象內(nèi)某一屬性進(jìn)行排序(過濾掉字符串,數(shù)值相比較排序)
const obj = [
{
pointName: '1幢',
pointId: '1024',
},
{
pointName: '4幢',
pointId: '1014',
},
{
pointName: '2幢',
pointId: '1004',
},
{
pointName: '3幢',
pointId: '1024',
},
];
const sortBuildName = (property) => {
return (a, b) => {
const value1 = a[property].substr(0, a[property].length - 1);
const value2 = b[property].substr(0, b[property].length - 1);
return value1 - value2;
};
};
obj.sort(sortBuildName('pointName'));
排序前
排序前
排序后
排序后
2.不傳參,將按照字符編碼進(jìn)行排序
const arr = ['General','Tom','Bob','John','Army'];
arr.sort();
輸出:image.png
const arr2 = [30,10,111,35,1899,50,45];
arr2.sort();
image.png
3.傳入?yún)?shù),實(shí)現(xiàn)升序/降序排序
const arr3 = [30,10,111,35,1899,50,45];
arr3.sort((a, b) => {
return a -b;
})
輸出:image.png
const arr4 = [30,10,111,35,1899,50,45];
arr4.sort((a, b) => {
return b - a;
})
輸出:image.png
4.根據(jù)數(shù)組中的對象的多個(gè)屬性值排序,雙重排序
const jsonStudents = [
{name:"Dawson", totalScore:"197", Chinese:"100",math:"97"},
{name:"HanMeiMei", totalScore:"196",Chinese:"99", math:"97"},
{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){
var value1 = a.totalScore,
value2 = b.totalScore;
if(value1 === value2){
return b.Chinese - a.Chinese;
}
return value2 - value1;
});
輸出:image.png