I want to sum costs
with coefficients in done
object like this:
const costs = {a: 2000, b: 5000, c: 4000}
const done = {a: 1, b: 1, c: 2}
(1 * 2000) + (1 * 5000) + (2 * 4000) = 15000
I tried this with no luck:
function sumObjectsByKey(...objs) {
return objs.reduce((a, b) => {
for (let k in b) {
if (b.hasOwnProperty(k))
a[k] += (a[k] || 0) * b[k];
}
return a;
}, {});
}
console.log(sumObjectsByKey(obj1, obj2, obj3));
Any suggestions?
4
Answers
const costs = {a: 2000, b: 5000, c: 4000};
const done = {a: 1, b: 1, c: 2};
const total = Object.keys(done).reduce((sum, key) => sum + (costs[key] || 0) * done[key], 0);
console.log(total); // 15000
It will give you the answer with costs and done
You can use nested
Array#reduce
operations for this task.I guess it’s not the fastest way, but here’s another approach.