I have a range of numbers as follows:
const a = ["11-50", "2-10", "1", "51-200"]
I would like to sort them properly like
["1", "2-10", "11-50", "51-200"]
I have tried both of these sort methods to no avail:
a.sort((a, b) => a - b)
a.sort()
We can try sorting on the lower bound number in each range:
const input = ["11-50", "2-10", "1", "51-200"];
input.sort(function(a, b) {
return parseInt(a.split("-")[0]) - parseInt(b.split("-")[0]);
});
console.log(input);
A little more formally, write some code to change representation from strings to numbers and back...
const string2Range = string => string.split('-').map(parseInt);
const range2String = range => `${range[0}-${range[1]}`;
Define what makes a range smaller than another...
// low value?
const compLow = (rangeA, rangeB) => rangeA[0] - rangeB[0]
// midpoint value?
const midpoint = range => (range[1] - range[0]) / 2;
const compMid = (rangeA, rangeB) => midpoint(rangeA) - midpoint(rangeB);
// something else??
Then transform, sort, transform back (assuming string output is desired)
let input = ["11-50", "2-10", "1", "51-200"]
let ranges = input.map(string2Range);
ranges.sort(compLow); // or another you define
let output = ranges.map(range2String)
Disclaimer: parseInt may not always do what you want, but with this example it should work!
a.sort((a, b) => parseInt(a) - parseInt(b));