Home > Net >  How to sort a dash-seperated range of numbers?
How to sort a dash-seperated range of numbers?

Time:03-29

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()

CodePudding user response:

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);

CodePudding user response:

Disclaimer: parseInt may not always do what you want, but with this example it should work!

a.sort((a, b) => parseInt(a) - parseInt(b));

CodePudding user response:

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)

CodePudding user response:

You could match numbers and if two numbers are available, take it for an adjusted sort.
Try this snippet-

a = ["11-50", "2-10", "1", "51-200"]

a.sort(function (a, b) {
  function getV(v) { return v.match(/\d /g); }
  var aa = getV(a),
    bb = getV(b);

  return aa[0] - bb[0] || (aa[1] || aa[0]) - (bb[1] || bb[0]);
});

console.log(a)

  • Related