React — Why does this line append rather than add

I have other ways of doing the same thing .. So I am not looking for a different solution to this problem … I am looking for an explanation as to why if I have defined a integer, it still concatenates with .map as if it were a string.

I have a basic set of data retrieved from an API:

"data":["8","8","12","1","7","4","2"]

If I map it using

let count = response.data.metrics.data.map((item) => + parseInt(item));

I am having a hard time understanding why it’s treating this as a string returning

88121743

When I feel like because I am parsing it as an integer it should add and come out with 42.

Is this just an issue just using .map? Can shortcut math functions be used here?

Here is my Reproducible Example

>Solution :

Your current approach using Array#map creates a new array with each element converted to a number. React renders this array as multiple text nodes, so it looks like a single string.

To sum the values, use Array#reduce with parseFloat/parseInt, the Number function, or the unary plus operator to convert each string to a number.

const visitCount = data.reduce((a,b) => a + parseFloat(b), 0);

Leave a Reply