Looking for a way in JavaScript to sort an array without altering the element order but creating a "grouping" feature.
Example Data:
[
{group: 'test', title: 'A'},
{group: 'test', title: 'B'},
{group: 'test2', title: 'C'},
{group: 'test', title: 'D'}
]
The goal is to use [].sort()
to achieve this final order:
[
{group: 'test', title: 'A'},
{group: 'test', title: 'B'},
{group: 'test', title: 'D'},
{group: 'test2', title: 'C'}
]
This means not changing the order of the first two items, only switching #3 and #4 based on their group. Using localeCompare
would reorganize the groups alphabetically, which is not desired; their original order should be maintained.
UPDATE: To clarify further, I do not want to rearrange the group order alphabetically, they should remain in the same sequence as they appear.