I have one parent's object, which contains several child's objects. On each of them, I have an array, and I want to sum those values.
dataArray = {
"dribbble":{
"username":"JeremDsgn",
"followers":242,
"diff":{
"data":[230, 231, 236, 238, 239, 239, 242]
}
},
"twitter":{
"username":"jeremdsgn",
"followers":"592",
"diff":{
"data":[576, 578, 578, 581, 584, 589, 592]
}
},
"behance":{
"username":"JeremDsgn",
"followers":17,
"diff":{
"data":[16, 15, 15, 16, 16, 16, 17]
}
}
}
So in my case, I would like to create a total array who sum value by value.
total = [822, 824, 829, 835, 839, 844, 851]
I have two loop to go through objects, and through arrays, but didn't works.
for (var site in dataArray) {
var total = [];
for (var i = 0; i < dataArray[site].diff.data.length; i++) {
total += parseInt(dataArray[site].diff.data[i]);
}
}
But it didn't affect value to the array for each index values, and it returns NaN.
There's a few problems with your code.
You are clearing the
totalarray each time you step in to the inner loop. To fix this, declare the array outside of both loops.You need to initialize
totalwith 7 indices (all starting at zero).You need to increment
totalat the specified index, i.e.total[i] +=:JSFiddle
Working Code
Also: When using parseInt always remember to specify the radix as the second parameter.