Skip to content

Instantly share code, notes, and snippets.

@cpburnz
Last active August 29, 2015 13:58
Show Gist options
  • Save cpburnz/9975800 to your computer and use it in GitHub Desktop.
Save cpburnz/9975800 to your computer and use it in GitHub Desktop.
A natural sort comparison function for use with Array.prototype.sort().
/*!
This Gist provides a natural sort comparison function for use with
`Array.prototype.sort()`.
Author: Caleb P. Burns
License: CC BY-SA 3.0 <http://creativecommons.org/licenses/by-sa/3.0/>
Version: 1.0.1
Source: <https://gist.github.com/cpburnz/9975800>
Note: This is derived from the natural sort implementation by thg435 <http://stackoverflow.com/users/989121/thg435>
posted at <http://stackoverflow.com/a/15479354/369450>.
*/
/**
This regular expression is used internally to split strings on numeric and
non-numeric boundaries.
*/
var _naturalCompare_regex = /(\d+|\D+)/g;
/**
This function is used internally to split a string into tokens on numeric and
non-numeric boundaries.
*/
var _naturalCompare_split = function(value) {
var split = [];
('' + value).replace(_naturalCompare_regex, function($0, $1) {
split.push($1);
});
return split;
};
/**
This comparison function implements natural sorting for use with
`Array.prototype.sort()`.
*/
var naturalCompare = function(left, right) {
var left_split = _naturalCompare_split(left);
var right_split = _naturalCompare_split(right);
while (left_split.length && right_split.length) {
var left_part = left_split.shift();
var right_part = right_split.shift();
var compare = (parseInt(left_part) - parseInt(right_part)) || left_part.localeCompare(right_part);
if (compare) {
return compare;
}
}
if (left_split.length) {
return -1;
} else if (right_split.length) {
return 1;
}
return 0;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment