Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

387
Views
How to sort a dash-seperated range of numbers?

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

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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)
about 4 years ago · Juan Pablo Isaza Report

0

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

a.sort((a, b) => parseInt(a) - parseInt(b));
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!