0

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 ?

3 Answers3

4

[0,10,10,0,10].reduce((sum, a) => sum + a, 0);

Satya S
  • 228
  • 1
  • 6
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)
MoRe
  • 2,296
  • 2
  • 3
  • 23
1

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
Pelicer
  • 1,348
  • 4
  • 23
  • 54