 |
|
6
ceet Oct 16, 2019 1
我们可以对任何对象类型的数组排序,比如,对象 Person 有名字和年龄属性,我们希望根据年龄排序,那么我们可以这么写:
const friends=[ {name:'john',age:30}, {name:"lily",age:20}, {name:"merry",age:24}, ]; function comparePerson(property){ return function(a,b){ if(a[property] < b[property]){ return -1; } if(a[property] > b[property]){ return 1; } return 0; } } console.log(friends.sort(comparePerson('age')));
这是最简单的根据年龄 age 排序,如果要排序的字段里面包含汉字或者英文字母要怎么排呢,我们可以这么写:
let data = [ {chinese: '蔡司', english: 'Chase'}, {chinese: '艾伦', english: 'Allen'}, {chinese: '左拉', english: 'Zola'}, {chinese: '贝克', english: 'Baker'}, {chinese: '伯格', english: 'Berg'}, {chinese: '菲奇', english: 'Fitch'}, {chinese: '迪安', english: 'Dean'}, {chinese: '厄尔', english: 'Earle'}, {chinese: '亨利', english: 'Henry'}, ]; //根据汉字首字母排序 //使用箭头函数 // [注] localeCompare() 是 js 内置方法 // data.sort((a, b)=> b.chinese.localeCompare(a.chinese, 'zh')); //z~a 排序 // data.sort((a, b)=> a.chinese.localeCompare(b.chinese, 'zh')); //a~z 排序 // console.log(data);
//根据英文排序 比较 首字母 ASCLL 码 // console.log(data[0].english.charCodeAt(0)); // data.sort((a, b) => b.english.charCodeAt(0) - a.english.charCodeAt(0)); //z~a 排序 data.sort((a, b) => a.english.charCodeAt(0) - b.english.charCodeAt(0)); //a~z 排序
console.log(data);
|