欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JavaScript中对象数组 根据某个属性值进行排序

程序员文章站 2024-03-04 11:21:41
...

将下列对象数组,通过工资属性,由高到低排序

 

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});

 

JavaScript中对象数组 根据某个属性值进行排序

那么考点在哪里呢?实际上在于数组对象的sort方法。

Array.sort(fun)

fun是一个函数,排序根据这个函数返回值来进行判断,如果返回值小于0表示两个元素不需要交换位置,1表示要用交互位置,0表示相等,实际上<=0等效。

sort方法有两个注意点:

  1. 会操作原始数组,经过操作后原始数组发生变化
  2. 默认排序按照字符编码排序,例如,我们有下面的一个例子:

 https://www.cnblogs.com/webcabana/p/7460038.html

 JavaScript中对象数组 根据某个属性值进行排序

需要定义下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