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"
}
]
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);
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);