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

226
Vistas
Javascript code to find the Total number of values between different ranges and also add single numbers

I have few lists like this

a = [ 2, 47-54, 68-69, 120-121, 318, 320, 342, 364-366, 414-422, 503-505, 513-514, 529, 554, 586, 690, 775, 913, 1018, 1117, 1159, 1183, 1218-1219, 1379, 1478, 1491, 1497, 1510, 1562, 1601, 1664, 1673, 1686, 1692, 1710, 1759-1765, 1862-1881, 1951-1962, 1992, 2020 ]

b = [ 18, 28, 34-35, 58-84, 110-137, 139-191, 193-272 ]
value of b = 192

Trying to get a simple javascript code to get the total number of values between different ranges and also add single numbers as I have mentioned for the value of b.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

you can do something like this

const b = [ '18', '28', '34-35', '58-84', '110-137', '139-191', '193-272' ]

const calculateTotalNumbers = data => data.reduce((res, n) => {
  const [n1, n2] = n.split('-').map(Number)
  if(n2){
    return res + n2 - n1 + 1
  }
  return res + 1
}, 0)

console.log(calculateTotalNumbers(b))

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can do it using Array.prototype.reduce.

const 
  lines = ["18", "28", "34-35", "58-84", "110-137", "139-191", "193-272"],
  result = lines.reduce((r, line) => {
    const [start, stop = start] = line.split("-").map(Number);
    return r + stop - start + 1;
  }, 0);

console.log(result);

Note: To handle single lines I've defaulted stop to start.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can iterate over the values in the array using reduce, splitting values on a - and adding either 1 (when there is no -) or the difference between the end and start values (+1 for inclusive ranges) to the result:

const b = ['18', '28', '34-35', '58-84', '110-137', '139-191', '193-272']

const numsInc = (arr) => arr.reduce((acc, v) => {
  [s, e] = v.split('-');
  acc += e ? parseInt(e,10)-parseInt(s,10)+1 : 1
  return acc;
}, 0)

const numsExc = (arr) => arr.reduce((acc, v) => {
  [s, e] = v.split('-');
  acc += e ? parseInt(e,10)-parseInt(s,10) : 1
  return acc;
}, 0)

console.log(numsInc(b))
console.log(numsExc(b))

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