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.c
Solution 1:
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;
});
Solution 2:
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;
});
Solution 3:
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; }
Post a Comment for "Can I Make This Function More Concise"