Below is an array containing items:
var myArray =
[
{catNum : 'CAT I #4', trackingNumber : 'ORG Cat-123'},
{catNum : 'CAT I #6', trackingNumber : 'ORG Dog-345'},
{catNum : 'CAT I #2', trackingNumber : 'ORG Cat-123'},
{catNum : 'CAT I #2', trackingNumber : 'ORG Cat-345'},
{catNum : 'CAT II #15', trackingNumber : 'ORG Fish-264'},
{catNum : 'CAT III #1', trackingNumber : 'ORG Bird-123'},
{catNum : 'CAT II #7', trackingNumber : 'ORG Dog-533'},
]
The goal is to sort the array first by catNum, and then by the tracking number in case of identical catNums.
Initially, sorting was accomplished for catNum property using the code below:
myArray.sort(function mySort(a, b)
{
return catTrackSort(a, b);
});
function catTrackSort(a, b)
{
var left = a.catNum.match(/CAT ([IV]+) #([0-9]+)/);
var right = b.catNum.match(/CAT ([IV]+) #([0-9]+)/);
if (left[1].length === right[1].length)
{
return left[2] - right[2];
}
else
{
return left[1].length - right[1].length;
}
}
To further refine the sorting process based on alphabetical order of the trackingNumber when catNum values are the same, the following attempt was made:
function catTrackSort(a, b)
{
var left = a.catNum.match(/CAT ([IV]+) #([0-9]+)/);
var right = b.catNum.match(/CAT ([IV]+) #([0-9]+)/);
if (left[1].length === right[1].length)
{
if (left[2] === right[2])
{
var left1 = a.trackingNumber.match(/ORG ([A-Z]+)/);
var right2 = b.trackingNumber.match(/ORG ([A-Z]+)/);
return left1[1] - right1[1];
}
else return left[2] - right[2];
}
else
{
return left[1].length - right[1].length;
}
}
If you have any suggestions or corrections on how to achieve the desired sorting, please share them.