Skip to content
Advertisement

Sum all similar keys in an array with a random number of keys and array items

My Array (can have several items, and there can be multiple ‘keys’ other than ‘companyName’):

myarray = [
    { companyName: 'X', randomKey: 10, randomKey2: 90, ...},
    { companyName: 'X', randomKey: 30, randomKey2: 81, ...},
    { companyName: 'X', randomKey: 930, randomKey2: 93, ...},
    { companyName: 'X', randomKey: 20, randomKey2: 23, ...},
    { companyName: 'X', randomKey: 10, randomKey2: 10, ...},
    { companyName: 'X', randomKey: 11, randomKey2: 40, ...},
    ....
]

randomKey and randomKey2 are only examples. The key names can be anything and there can be 1 or more in each array item.

Expected results:

[
    { companyName: 'X', randomKey: 1011, randomKey2: 337, ...},
]

companyName: ‘X’ is a fixed value, and all of the items have this

Attempted:

   this.myarray.reduce((acc, curr) => {
      let ind = b.findIndex(e => e.companyName === curr.companyName);
      if (ind > -1) {
          acc[ind][c] = +acc[ind][c] + +a[c]
      } else {
          a[c] = +a[c] || 0
         acc.push(curr)
      }
      return b;
   }, []);

But it leads to [{x: NaN}].

How can I fix this?

Advertisement

Answer

You can play around with this example

const myArray = [
    { companyName: 'X', randomKey: 10, randomKey2: 90 },
    { companyName: 'X', randomKey: 30, randomKey2: 81 },
    { companyName: 'X', randomKey: 930, randomKey2: 93 },
    { companyName: 'X', randomKey: 20, randomKey2: 23 },
    { companyName: 'X', randomKey: 10, randomKey2: 10 },
    { companyName: 'X', randomKey: 11, randomKey2: 40 },
    { companyName: 'Y', randomKey: 11, randomKey2: 45, randomKey3: 4 },
    { companyName: 'Y', randomKey: 21, randomKey2: 46 },
];

const results = {};

const addKeyValue = (target, data) => {
  const keys = [...new Set([...Object.keys(target), ...Object.keys(data)])];

  keys.forEach((key) => {
    target[key] = target[key] || 0;
    target[key] += data[key] || 0;
  });

  return target;
};

myArray.forEach(({ companyName, ...data }) => {
  if (results[companyName] === undefined) {
    results[companyName] = { ...data };
  } else {
    results[companyName] = addKeyValue(results[companyName], data);
  }
});

console.log(results);

https://jsfiddle.net/gre6Ly1a/1/

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement