Last active
August 29, 2015 14:17
-
-
Save astockwell/bb441dc332ebfe4f5e8b to your computer and use it in GitHub Desktop.
Sort array of string numbers correctly
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// JsFiddle: http://jsfiddle.net/astockwell/6jxLeppm/4/ | |
// Array.prototype.filter polyfill for <= IE8 | |
if (!Array.prototype.filter) {Array.prototype.filter = function(fun/*, thisArg*/) {if (this === void 0 || this === null) {throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; if (typeof fun !== 'function') {throw new TypeError(); } var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) {if (i in t) {var val = t[i]; if (fun.call(thisArg, val, i, t)) {res.push(val); } } } return res; }; } | |
var containsNoNumbers = function(s) { | |
return s.indexOf('0') === -1; | |
}; | |
var containsNumbers = function(s) { | |
return !containsNoNumbers(s); | |
}; | |
var getDigitsOnly = function(s) { | |
return parseInt(s.replace(/\D/g, '')); | |
}; | |
var correctlyOrderStringsWithNumbers = function(a, b) { | |
x = getDigitsOnly(a); | |
y = getDigitsOnly(b); | |
return x - y; | |
}; | |
var fieldStringArray = ["No Authority", "Up to 1,000", "Up to 10,000", "IT Request", "Up to 100,000", "Up to 25,000", "Up to 5,000", "Up to 50,000"]; | |
var nonNumericOptions = fieldStringArray.filter(containsNoNumbers).sort(); | |
// => ["IT Request", "No Authority"] | |
var numericOptions = fieldStringArray.filter(containsNumbers); | |
// => ["Up to 1,000", "Up to 10,000", "Up to 100,000", "Up to 25,000", "Up to 5,000", "Up to 50,000"] | |
var sortedNumericOptions = numericOptions.sort(correctlyOrderStringsWithNumbers); | |
// => ["Up to 1,000", "Up to 5,000", "Up to 10,000", "Up to 25,000", "Up to 50,000", "Up to 100,000"] | |
var sortedFieldStringArray = nonNumericOptions.concat(sortedNumericOptions); | |
// => ["IT Request", "No Authority", "Up to 1,000", "Up to 5,000", "Up to 10,000", "Up to 25,000", "Up to 50,000", "Up to 100,000"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment