Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading