I have an array, productData
with multiple properties. This is how I currently sort the array by monthlyCost
, ascending.
How can I modify this to sort all items by a boolean property isPromoted
, followed by monthlyCost
?
My array should start with all items where isPromoted == true
sorted by monthlyCost
, then all items where isPromoted == false
sorted by monthlyCost
.
JavaScript
x
10
10
1
productData.sort((a, b) => {
2
if (a.monthlyCost > b.monthlyCost) {
3
return 1;
4
} else if (a.monthlyCost < b.monthlyCost) {
5
return -1;
6
} else {
7
return 0;
8
}
9
});
10
Advertisement
Answer
You can use this callback:
JavaScript
1
2
1
productData.sort((a, b) => +b.isPromoted - +a.isPromoted || a.monthlyCost - b.monthlyCost);
2
The unary plus is optional in plain JavaScript, but in a TypeScript context, you’ll need to be explicit about the conversion to number and apply +
.