I have this array of objects:
[{a:5,b:2},{a:10,b:20},{a:1,b:3},{a:8,b:12}]
And I must sort it in different ways. For example for order = 1 the order must be like this:
1.- {a:8,b:12} 2.- {a:10,b:20} 3.- {a:1,b:3} 4.- {a:5,b:2}
If order = 2
1.- {a:10,b:20} 2.- {a:1,b:3} 3.- {a:8,b:12} 4.- {a:5,b:2}
If order = 3
1.- {a:5,b:2} 2.- {a:1,b:3} 3.- {a:8,b:12} 4.- {a:10,b:20}
I know I can create a new array and pushing the elements according the different orders like this
if(order === 1) {
oldArray.reduce((a, obj) => {
if (obj.a === 8) {
newArray.push(obj);
}
return a;
}, []);
oldArray.reduce((a, obj) => {
if (obj.a === 10) {
newArray.push(obj);
}
return a;
}, []);
}
And so on, is there a way to fix it with fewer lines of code?
ordernumber and the actual order? Or is it like completely custom/random?array.sortmethod.orderand the elements.oldArray? Does the input ever change? And if yes, in what ways? It sounds like you could simply hardcode a few constants and return the one for respectiveorder.switch-casestatement.