Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

93
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda