这是对对象数组进行排序的正确方法吗?:
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/