Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

219
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda