將下列對象數組,通過工資屬性,由高到低排序
var BaiduUsers = [], WechatUsers = [];
var User = function(id, name, phone, gender, age, salary) {
this.id = id;
this.name = name;
this.phone = phone;
this.gender = gender;
this.age = age;
this.salary = salary;
};
User.create = function(id, name, phone, gender, age, salary) {
return new User(id, name, phone, gender, age, salary);
};
BaiduUsers.push(User.create(1, 'tommy', '1111','male', 18, 2800));
BaiduUsers.push(User.create(2, 'jerry', '2222','male', 28, 5800));
BaiduUsers.push(User.create(3, 'raobin','3333','female', 14, 1200));
BaiduUsers.push(User.create(4, 'binbin','4444','male', 23, 9800));
BaiduUsers.push(User.create(5, 'arthur','5555','female', 22, 3000));
WechatUsers.push(User.create(1, 'tommy', '1111','male', 20, 4000));
WechatUsers.push(User.create(2, 'allen', '6666','male', 34, 15800));
WechatUsers.push(User.create(3, 'raobin','3333','female', 16, 2300));
WechatUsers.push(User.create(4, 'harvey','7777','male', 30, 29800));
WechatUsers.push(User.create(5, 'yuyu', '8888','female', 27, 7000));
對於一般的數組,可以用sort函數,對於對象數組呢
var points = [40,100,1,5,25,10];
points.sort(function(a,b){return a-b});
那么考點在哪里呢?實際上在於數組對象的sort方法。
Array.sort(fun)
fun是一個函數,排序根據這個函數返回值來進行判斷,如果返回值小於0表示兩個元素不需要交換位置,1表示要用交互位置,0表示相等,實際上<=0等效。
sort方法有兩個注意點:
會操作原始數組,經過操作后原始數組發生變化
默認排序按照字符編碼排序,例如,我們有下面的一個例子:
https://www.cnblogs.com/webcabana/p/7460038.html
需要定義下sortBy方法,然后進行調用即可
BaiduUsers.sort(sortBy("salary"))
如果存在工資相等的情況,要求按照年紀排序,應該如何定義SortBY方法呢?
var BaiduUsers = [], WechatUsers = [];
var User = function(id, name, phone, gender, age, salary) {
this.id = id;
this.name = name;
this.phone = phone;
this.gender = gender;
this.age = age;
this.salary = salary;
};
User.create = function(id, name, phone, gender, age, salary) {
return new User(id, name, phone, gender, age, salary);
};
BaiduUsers.push(User.create(1, 'tommy', '1111','male', 18, 10000));
BaiduUsers.push(User.create(2, 'jerry', '2222','male', 28, 10000));
BaiduUsers.push(User.create(3, 'raobin','3333','female', 14, 1200));
BaiduUsers.push(User.create(4, 'binbin','4444','male', 23, 9800));
BaiduUsers.push(User.create(5, 'arthur','5555','female', 22, 10000));
function sortBy(field1,field2) {
return function(a,b) {
if(a.field1 == b.field1) return a.field2 - b.field2;
return a.field1 - b.field1;
}
}
BaiduUsers.sort(sortBy("salary","age"));
貌似不正確ing