Is this the correct way to sort an array of objects?:
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)
}
When I look at the documentation:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
They are doing this instead, which seems extremely awkward:
a.sort((x,y)=>
{
if(x.a>y.a) return 1;
if(x.a<y.a) return -1;
return 0;
});
x.a - y.asortshould return 3 values.1for greater than,0for no change and-1for less than.-would work. For numeric values, it will work, but as OP is asking for better approach, I guess we should consider both situations<or>, it would be coerced to a number