一、排序
1.根据对象内某一属性进行排序(过滤掉字符串,数值相比较排序)
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.不传参,将按照字符编码进行排序
const arr = ['General','Tom','Bob','John','Army'];
arr.sort();
输出:
image.png
const arr2 = [30,10,111,35,1899,50,45];
arr2.sort();
3.传入参数,实现升序/降序排序
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.根据数组中的对象的多个属性值排序,双重排序
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
网友评论