JavaScript 中如何对数组中对象的某个属性值进行排序呢,如何对字符串排序呢?
array 本身有一个sort()方法,可以对数字类型直接排序,
array 还有另外一个 reverse()方法,可以将当前的排序倒过来
例子:
let arr1= [4,6,3,2,7,35,65];
compareUp = (val1,val2) =>{
return val1-val2;
};
compareDown = (val1,val2) =>{
return val2-val1;
};
console.log(arr1.sort(compareUp )); // [2, 3, 4, 6, 7, 35, 65]
console.log(arr1.sort(compareUp ).reverse()); // [65, 35, 7, 6, 4, 3, 2]
console.log(arr1.sort(compareDown)); // [65, 35, 7, 6, 4, 3, 2]
console.log(arr1.sort(compareDown).reverse()); // [2, 3, 4, 6, 7, 35, 65]
下边就来看如何对对象中某个属性进行排序
例子:通过名字进行排序
let data = [
{name : 'Bob', score : '95', age : '18'},
{name : 'Amy', score : '86', age : '18'},
{name : 'Coco',score : '36',age : '18'},
{name : 'Mark',score : '80', age : '18'},
{name : 'Frank',score : '40',age : '18'}
];
compare = (val1,val2) =>{
return val1.name.toLowerCase() > val2.name.toLowerCase();
};
console.log(data.sort(compare)); // 结果根据名字从 A-Z 顺序排列
结果如下