It looks like you are always appending to the variable aka +=. If you don't reset it back to zero when you call the function then you will just get an incrementally large result. Like if I did
Code:
<script>
var x = 0;
function AddTen()
{
x += 10;
}
</script>
X would get ten larger every time I called the function. If I wanted X to only be 10 then I would have to put the x = 0 inside the function. (or just make the function x = 10, but I'm sure you see my point)
Yes you are rigth. The problem is that inside the expression res.__array.push(res[obj.shapeId] = obj); I assign the object itself to the res, not a clone. With res[obj.shapeId].number += obj.number; then it manipulates the original object, which is why the results grow in subsequent calls.
Better:
Code:
var numberSums = allMarkers.reduce(function(res, obj) {
var id = obj.shapeId;
if (id in res)
res[id] += obj.number;
else
res[id] = obj.number;
return res;
}, {});
Object.keys(numberSums).sort(function(a,b){return a-b;}).forEach(function(id) {
alert(id+": "+numberSums[id]);
});
Bookmarks