skip to Main Content

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


  1. const costs = {a: 2000, b: 5000, c: 4000};
    const done = {a: 1, b: 1, c: 2};
    
    let total = 0;
    
    for (let key in done) {
        total += done[key] * costs[key];
    }
    
    console.log(total); // Output: 15000
    
    or
    
    const costs = {a: 2000, b: 5000, c: 4000};
    const done = {a: 1, b: 1, c: 2};
    
    const total = Object.keys(done).reduce((sum, key) => {
        return sum + (done[key] * costs[key]);
    }, 0);
    
    console.log(total); // Output: 15000
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
  3. You can use nested Array#reduce operations for this task.

    const costs = {a: 2000, b: 5000, c: 4000},
          done = {a: 1, b: 1, c: 2};
    
    const sumObjectsByKey = (...objs) => Object.keys(objs[0] ?? {})
      .reduce((tot, k) => tot + objs.reduce((a, o) => a * o[k], 1), 0);
    
    // assuming first object has all the keys
    
    console.log(sumObjectsByKey(costs, done));
    Login or Signup to reply.
  4. I guess it’s not the fastest way, but here’s another approach.

    const sumObjectsByKey = (...objects) => {
      const transformed = {};
      objects.forEach((obj) => {
        for (const key in obj) {
          transformed[key]?.length
            ? transformed[key].push(obj[key])
            : (transformed[key] = [obj[key]]);
        }
      });
    
      let result = 0;
    
      for (const key in transformed) {
        result += transformed[key].reduce(
          (acc, next) => (acc ? acc * next : next),
          0,
        );
      }
    
      return result;
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search