I am trying to figure a way in JS to sort an array without actually changing the order of the elements but have more like a "grouping" feature.
Sample Data:
[
{group: 'test', title: 'A'},
{group: 'test', title: 'B'},
{group: 'test2', title: 'C'},
{group: 'test', title: 'D'}
]
My idea is to do an [].sort()
the way that my final order is:
[
{group: 'test', title: 'A'},
{group: 'test', title: 'B'},
{group: 'test', title: 'D'},
{group: 'test2', title: 'C'}
]
Means: I did not change the order of the first two items but only switched #3 and #4 because of their group. If I'd do with a classical localeCompare
, I'd end up with my groups being restored based on their value which is not what I want, their order should be kept.
EDIT: Considering the answers, I want to re-clarify that I do not want to change the order of the groups, means they should not be alphabetically sorted but instead, they should be groupped by the order they appear.