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

94
Views
Order javascript array of numbers with ranges

I'm building an array by passing in individual numbers and ranges of numbers as strings and I want to be able to perform a function on this array and return a comma separated string, firstly by order of the numbers and also grouped if they exist.

For example I have

['13','2','1','7-9','14','3','15-16','20']

And I'd like to be able to get the following result from it:

'1-3,7-9,13-16,20'

This is what I have attempted so far:

function getRangeValues(range) 
{
    var start = Number(range.split('-')[0]);
    var end = Number(range.split('-')[1]);
    return Array(end - start + 1).fill().map((_, idx) => start + idx)
}

var splitArray = [];
var originalArray = ['13','2','1','7-9','14','3','15-16','20']
originalArray.forEach(e => {
    e.includes('-') ? 
        splitArray.push(...getRangeValues(e)) 
        : splitArray.push(parseInt(e))
});
splitArray.sort(function(a, b){return a - b});

console.log(splitArray)
// returns [1, 2, 3, 7, 8, 9, 13, 14, 15, 16, 20]

How do I loop through this new array to figure out what ranges exist within it and then return a string showing the ranges and individuals values in ascending order?

For example:

'1-3,7-9,13-16,20'
about 4 years ago · Juan Pablo Isaza
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!