I need to order an array of objects by the property price
.
Right now I have the following, which works as intended:
function orderByPriceASC(a,b) {
return(
a.price < b.price ? -1
: a.price > b.price ? 1
: 0
);
}
function orderByPriceDESC(a,b) {
return(
a.price < b.price ? 1
: a.price > b.price ? -1
: 0
);
}
function sortByPrice(order) {
setProductList((prevState) => {
const aux = Array.from(prevState);
order === 'asc' ? aux.sort(orderByPriceASC) : aux.sort(orderByPriceDESC);
return aux;
});
}
But can is there a way that I can structure this so I can get a single compare function that works for both ASC and DESC order?
Something like:
function orderByPrice(a,b,order) {
return(
a.price < b.price ?
order === 'asc' ? -1 : 1
: a.price > b.price ? 1
order === 'asc' ? 1 : -1
: 0
);
}
The problem is that I would have to send that extra parameter down to the Array.sort
method which I don't think it's possible. Maybe with some wrapper function.
How can this be implemented?