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

96
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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