I'm building a functional React component that allows a list of products to be sorted by various properties. The properties could be top-level or nested properties. And I'd also like a sort order to be defined. As a secondary sort, I'd like a name
property to be used.
I have left out the React parts to boil it down to the plain JS.
Here's my first take on it:
sort = [one-of-the-cases]
ascending = [true||false]
const sortFunc = (a, b) => {
let aParam = null
let bParam = null
switch (sort) {
case 'brand':
aParam = a.brand.title
bParam = b.brand.title
break
case 'weight':
aParam = a.metadata.weight
bParam = b.metadata.weight
break
case 'price':
aParam = a.price.unit_amount
bParam = b.price.unit_amount
break
case 'style':
aParam = a.metadata.style
bParam = b.metadata.style
break
case 'arrival':
aParam = b.created
bParam = a.created
break
default:
aParam = a.brand.title
bParam = b.brand.title
break
}
// Sort by property, ascending or descending
if (aParam < bParam) {
return ascending ? -1 : 1
}
if (aParam > bParam) {
return ascending ? 1 : -1
}
// Sort by name
if (a.name < b.name) {
return -1
}
if (a.name > b.name) {
return 1
}
return 0
}
products.sort(sortFunc)
This seems overly complicated. One idea I have is to flatten the object to eliminate the nested properties, which would make it possible to store the sort param as a variable, and use bracket notation to reference the object property. This would eliminate the switch statement.
Any other ideas for simplifying this complicated sort?
ascending
intentionally from thename
comparison? \$\endgroup\$ – Roland Illig Jul 15 '20 at 22:16