whytheq whytheq - 26 days ago 5
Javascript Question

Can I make this function more concise

I have this javascript snippet and am wondering if I can calculate

amount
and
users
in a single pass of the
reduce
function?

root.children.forEach(function(v) {

v.amount = v.children.reduce(function(a, b) {
console.log(a);
return {
amount: a.amount + b.amount
}
}, {
'amount': 0
}).amount

v.users = v.children.reduce(function(a, b) {
console.log(a);
return {
users: a.users + b.users
}
}, {
'users': 0
}).users

})

Answer

You could a single Array#forEach loop.

var root = {
        children: [
            { children: [
                { amount: 2, users: 3 },
                { amount: 7, users: 5 }
            ]}
        ]
    };

root.children.forEach(function(v) {
    v.amount = 0;
    v.users = 0;

    v.children.forEach(function(a) {
        v.amount += a.amount;
        v.users += a.users;
    });
});
console.log(root);
.as-console-wrapper { max-height: 100% !important; top: 0; }