javascript - 对对象数组进行排序

标签 javascript sorting ecmascript-6

这是对对象数组进行排序的正确方法吗?:

class Alarm{
    constructor(data){
        this.a = data.a;
        this.b = data.b;
    }
}

const a1 = new Alarm({a:4,b:1});
const a2 = new Alarm({a:1,b:4});
const a3 = new Alarm({a:2,b:3});
const a4 = new Alarm({a:3,b:2});

let a = [a1,a2,a3,a4];

a.sort((x,y)=>x.a>y.a);

for(const i of a){
    console.log(i)
}

a.sort((x,y)=>x.b>y.b);

for(const i of a){
    console.log(i)
}

当我查看文档时:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

他们正在这样做,这看起来非常尴尬:

a.sort((x,y)=>
    {
        if(x.a>y.a) return 1;
        if(x.a<y.a) return -1;
        return 0;
    });

最佳答案

您可以使用差异进行排序

a.sort((x, y) => x.a - y.a);

取自 Array#sort

If compareFunction is supplied, the array elements are sorted according to the return value of the compare function. If a and b are two elements being compared, then:

  • If compareFunction(a, b) is less than 0, sort a to a lower index than b, i.e. a comes first.
  • If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
  • If compareFunction(a, b) is greater than 0, sort b to a lower index than a.
  • compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned then the sort order is undefined.

class Alarm{
    constructor(data){
        this.a = data.a;
        this.b = data.b;
    }
}

const a1 = new Alarm({a:4,b:1});
const a2 = new Alarm({a:1,b:4});
const a3 = new Alarm({a:2,b:3});
const a4 = new Alarm({a:3,b:2});

let a = [a1, a2, a3, a4];

a.sort((x,y) => x.a - y.a);

console.log(JSON.stringify(a, 0, 4));

关于javascript - 对对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40375909/

相关文章:

javascript - ng-click 值更改 + $scope.watch 绑定(bind)无法正常工作

java - 使用反向比较器对带有流的数组进行排序

c - 尝试使用调用 stat 的 ctime 返回值对 c 中的结构数组进行排序

javascript - 将 let 用于返回结果的变量是否安全?

javascript - 如何对 es6 模块进行功能检测

javascript - 如何检测 Snowflake VARCHAR 中的表情符号?

javascript - Jquery UI 模态对话框

php - 聚集活跃的访客;在数据库中为每个访问者分配一个唯一的用户行

mysql - 如何根据其他表中的条目对结果进行排序

javascript - Javascript ES6 中的静态构造函数