Reputation: 35557
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
})
Upvotes: 1
Views: 81
Reputation: 386570
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; }
Upvotes: 1
Reputation: 72857
It looks like you can literally combine the two methods into one:
root.children.forEach(function(v) {
var result = v.children.reduce(
function(a, b) {
return {
amount: a.amount + b.amount,
users: a.users + b.users
};
},
{ amount: 0, users: 0 }
); // ^ Note that I left out the quotes there. In this case, they're optional.
v.amount = result.amount;
v.users= result.users;
});
Upvotes: 6
Reputation: 67207
Yes you can do that like below,
root.children.forEach(function(v) {
var obj = v.children.reduce(function(a, b) {
a.amount += b.amount;
a.users += a.users;
}, {'amount': 0, 'users' : 0 });
v.amount = obj.amount;
v.users = obj.users;
});
Upvotes: 6