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

calculate JSON.stringify(obj) to sum value?

In my local storage I have some score value stored in array

var obj = localStorage.getItem("scoreList")

output

[0,10,10,0,10]

I want sum of this value like and return to data value

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

sum = 30

I have tried to convert into string value

var string = JSON.stringify(obj);
output "[0,10,10,0,10]"

How can I execute this sum value ?

>Solution :

localStorage.getItem("scoreList").replace(/(\[|\])/g, '').split(",").map(x => parseFloat(x)).reduce((a,b) => a+b, 0)

a simple way:

JSON.parse(localStorage.getItem("scoreList")).reduce((x, y) => x + y)
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