Ionko Gueorguiev Ionko Gueorguiev - 1 year ago 70
Javascript Question

reset a variable for a reusable function

I have a bit of code that counts how many objects are in the returned json and gives me the total number.

loadCountSetOne = 0;
$.each(dataSetOne.user.customers, function(key, val) {
loads = Object.keys(val.loads).length;
loadCountSetOne = loadCountSetOne + loads;

This works fine, but since I'll need to count these a bunch of times I thought I'd move it into it's own function and call it when I need it with something like

count = 0;
function counter(itemToCount) {
result = Object.keys(itemToCount).length;
count = count + result;
console.log(itemToCount, result, count);
return count;

When I call the function the 1st time I get the right result. When I call it again it adds the 2nd result to the 1st and so on.

My understanding is that that is what it's supposed to do, but not what I need it to do. I tried resetting the value for
is various places but it didn't work.

Is there a way to make this function give me a result based on the number of objects in
each time it's called?


Answer Source

You can't do this in the counter() function itself, since it has no way of distinguishing the first call (which should reset the variable) with subsequent calls. You could pass the array index, and it could reset the total when the index is 0, but this is not a good general solution because you might want to use the function in other ways.

You just need to reset the variable before the $.each() loop:

count = 0;
$.each(dataSetOne.user.customers, function(key, val) {

Or you could use reduce, which is designed for accumulating values.

function counter(total, itemToCount) {
    var result =  Object.keys(itemToCount).length;
    total += result;
    console.log(itemToCount, result, total);
    return total;

var count = dataSetOne.user.customers.reduce(function(total, current) {
    return counter(total, current.loads);
}, 0);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download