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

90
Visualizações
Using substring while using reduce()

I am trying to get the total length from an array using reduce. But I encountered a problem when I saw that the length was prefixed by 'km'. So I am trying to remove(substring) the 'km', then add the length. Here's what I've done so far:

this.totalLength= this.roads.map((road) => road.distance)
  .reduce((prev, next) => prev + parseFloat(next.substring(2)));

It is working but it is not adding the second value of the array to the totalLength.

Here's the sample of the array:

[
  {
    "Id": "1",
    "distance": "Km12.20",
    "name": "Hwy1"
  },
  {
    "Id": "2",
    "distance": "Km19.60",
    "name": "Hwy2"
  }
]
    
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I would recommend searching for a float using regex if you think it may be prefixed or suffixed by any other text. You can use the regex /(\d*\.)?\d+/ to do so.

Additionally, <Array>.reduce takes an additional parameter for the starting value, so make sure to provide that.

this.totalLength= this.roads.map((road) => road.distance)
  .reduce((prev, next) => prev + (parseFloat(next.match(/(\d*\.)?\d+/)[0])||0), 0);
about 4 years ago · Juan Pablo Isaza Relatório

0

What you did is almost correct. reduce also expects a second argument which is the initial value.

const roads = [
  {
    "Id": "1",
    "distance": "Km12.20",
    "name": "Hwy1"
  },
  {
    "Id": "2",
    "distance": "Km19.60",
    "name": "Hwy2"
  }
]

roads
  .map((road) => road.distance)
  .reduce((prev, next) => prev + parseFloat(next.substring(2)), 0);

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