javascript-natural-sort
javascript-natural-sort copied to clipboard
Incorrect sort of leading zeros within an alphanumeric value
The result of this array is incorrect:
["a55", "a010", "a102", "a02", "a1", "a255", "a33", "a43", "a87"].sort( naturalSort );
// result : ["a010", "a02", "a1", "a33", "a43", "a55", "a87", "a102", "a255"]
My feeble attempts at fixing this problem caused the failure of a few other unit tests.
LOL ok I think this is a quick & easy solution:
normChunk = function(s, l) {
// normalize spaces; find floats not starting with '0', string or 0 if not defined (Clint Priest)
return (naturalSort.ignoreLeadingZeros || !s.match(ore) || l == 1) && parseFloat(s) || s.replace(snre, ' ').replace(sre, '') || 0;
},
This just adds a naturalSort.ignoreLeadingZeros
option; then for a unit test just add this:
naturalSort.ignoreLeadingZeros = true;
wrapTest(
["a55", "a010", "a102", "a02", "a1", "a255", "a33", "a43", "a87"],
["a1", "a02", "a010", "a33", "a43", "a55", "a87", "a102", "a255"],
"issue - leading zero in alphanumeric");
naturalSort.ignoreLeadingZeros = false;
And btw, this is the same issue as #6... I just realized that it was a duplicate.