Sort with a single comparator function:
var strings = ['0.1', '1,000,000.75', '10', '<100', '<20', '<40', '>1,000', '>100']; var sort = { regular: 1, reverse: -1 }; var sortOrder = sort.regular; function compare(a, b) { function toNum(str) { return +str.replace(/[^0-9.-]/g, ''); } function range(str) { return { '<': -1, '>': 1 }[str[0]] || 0; } var rangeA = range(a); var rangeB = range(b); var score = rangeA === rangeB ? toNum(a) - toNum(b) : rangeA - rangeB; return score * sortOrder; } strings.sort(compare);
The range() function checks to see if a string starts with '<' or '>' and sets the value that is used for sorting if the strings have different ranges. Otherwise, strings are converted to numbers and simply sorted as numbers.
In the sample input, the resulting array is strings :
["<20", "<40", "<100", "0.1", "10", "1,000,000.75", ">100", ">1,000"]
You can play with him on:
https://jsfiddle.net/eyb7t3jz/8
Edited by:
Added sortOrder .
source share