Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

88
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!