My task in JavaScript involves sorting within a single sort() function that is passed as a parameter.
Specifically, I need to sort objects first by category and then further sort them by subcategory using:
return item1.category.localeCompare(item2.category) : item1.subCategory.localeCompare(item2.subCategory)
However, for objects without a category, I want to place them at the bottom of the list. The current approach I'm using does this but the items are not grouped together by subcategory as desired.
Here's an example of how the sorted objects look now:
[
{'category':'cat1', 'subcategory':'subcat1'},
{'category':'cat1', 'subcategory':'subcat2'},
{'category':'cat2', 'subcategory':'subcat1'},
{'category':'cat2', 'subcategory':'subcat2'}
{'category':'', 'subcategory':'subcat1'},
{'category':'', 'subcategory':'subcat2'},
{'category':'', 'subcategory':'subcat1'},
{'category':'', 'subcategory':'subcat2'}
]
I would like the final result to be organized by subcategory with empty categories staying grouped together. For instance:
[
{'category':'cat1', 'subcategory':'subcat1'},
{'category':'cat1', 'subcategory':'subcat2'},
{'category':'cat2', 'subcategory':'subcat1'},
{'category':'cat2', 'subcategory':'subcat2'}
{'category':'', 'subcategory':'subcat1'},
{'category':'', 'subcategory':'subcat1'},
{'category':'', 'subcategory':'subcat2'},
{'category':'', 'subcategory':'subcat2'}
]