I want to sort this JSON array based on unitId
var array = [
{ id: 10, unitId: 'unit17' },
{ id: 11, unitId: 'unit19' },
{ id: 13, unitId: 'unit27' },
{ id: 12, unitId: 'unit2' },
{ id: 13, unitId: 'unit11' },
{ id: 14, unitId: 'unit1'}
];
I want an output array like this
var array = [
{ id: 14, unitId: 'unit1' },
{ id: 12, unitId: 'unit2' },
{ id: 13, unitId: 'unit11' },
{ id: 10, unitId: 'unit17' },
{ id: 11, unitId: 'unit19'},
{ id: 13, unitId: 'unit27' }
];
2
Answers
To sort the given array based on the alphanumeric unitId, you can use the sort() method with a custom comparator function. Here’s an example:
This will output the desired sorted array:
The sort() function takes a custom comparator that compares two elements a and b. The unitId values are first stripped of the ‘unit’ string and then converted to integers using parseInt(). The difference between the unitId integers is returned to determine the sort order.
You can also use regex combination by replacing all non-digit numbers with empty string and then compare it.