'calculate JSON.stringify(obj) to sum value of string? [duplicate]
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
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 1:[1]
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)
Solution 2:[2]
[0,10,10,0,10].reduce((sum, a) => sum + a, 0);
Solution 3:[3]
If you set the scoreList value as an array, that is:
localStorage.setItem('scoreList', [0,10,10,0,10])
When you get it back it will still be a string, so there's no need for any other kind of validation or data type transformation as you did with JSON.stringfy. The following shoud be enough:
const obj = localStorage.getItem("scoreList")
const total = obj.reduce((sum, item) => sum + item, 0);
//total = 30
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Satya S |
| Solution 3 | Pelicer |
