Let’s say I have this array:
const services = [
{ id: 100, priority: 'Y', count: 300, payout: '30', id_region: 137 },
{ id: 101, priority: 'N', count: 200, payout: '40', id_region: 153 },
{ id: 102, priority: 'Y', count: 400, payout: '30', id_region: 137 },
{ id: 103, priority: 'Y', count: 500, payout: '50', id_region: 153 },
{ id: 104, priority: 'Y', count: 800, payout: '80', id_region: 222 }
];
And this global variable:
var regionsFound = ['153'];
I want to sort:
- first the id_region if that appears in regionsFound
- then priority ‘Y’ first
- then highest payout
- then the id_region if that doesn’t appear in regionsFound
- then count
Here’s my code:
services.sort((a, b) => {
if (regionsFound.indexOf(a.id_region.toString()) >= 0 && regionsFound.indexOf(b.id_region.toString()) >= 0){
if (a.priority == 'Y' && b.priority == 'N'){
return -1;
} else if (a.priority == 'N' && b.priority == 'Y'){
return 1;
}
return b.payout - a.payout;
} else if (regionsFound.indexOf(a.id_region.toString()) >= 0 && regionsFound.indexOf(b.id_region.toString()) < 0){
return -1;
} else {
return b.count - a.count;
}
});
So the result should be:
const services = [
{ id: 103, priority: 'Y', count: 500, payout: '50', id_region: 153 },
{ id: 101, priority: 'N', count: 200, payout: '40', id_region: 153 },
{ id: 104, priority: 'Y', count: 800, payout: '80', id_region: 222 },
{ id: 102, priority: 'Y', count: 400, payout: '30', id_region: 137 },
{ id: 100, priority: 'Y', count: 300, payout: '30', id_region: 137 }
];
I don’t know where’s the error.
HERE’S THE FINAL CODE AFTER THE COMMENTS:
services.sort((a, b) => {
let aInRegionsFound = regionsFound.includes(String(a.id_region));
let bInRegionsFound = regionsFound.includes(String(b.id_region));
if (aInRegionsFound && !bInRegionsFound){
return -1;
} else if (!aInRegionsFound && bInRegionsFound){
return 1;
} else if (!aInRegionsFound && !bInRegionsFound){
return b.count - a.count;
} else {
if (a.priority == 'Y' && b.priority == 'N'){
return -1;
} else if (a.priority == 'N' && b.priority == 'Y'){
return 1;
}
return parseFloat(b.payout) - parseFloat(a.payout);
}
});
4
Answers
You almost had it, you just need to convert
payout
values to numerical numbers first before you can sort them correctly.I also changed
indexof
forinclude
to have a cleaner codeI think you’ll save yourself a lot of headache if you don’t nest your if statements. Something like this should do the trick:
You can chain subtract operations with
||
given that-
operator converts its operands to numbers.For the region lookup I recommend use
Set
.It’s not clear how
id_region
is sorted, just swapa
andb
if needed.Use sort function for multiple sort criteria based on index value like this