Search code examples
javascriptlodash

_.sumBy total for same key across arrays


I'm struggling to get an output of all values of the same key across arrays in object. The output is merely a total sum(addition). Using lodash I have tried with sumBy.

// Here is my data:(question - how do I reformat the data below
// into one array as I think that would help)
const competitions = {
  0: {gameScore: "2", reportDate: "2018-05-09", oldvalue: 2},
  1: {gameScore: "3", reportDate: "2018-01-09", oldvalue: 1},
  2: {gameScore: "4", reportDate: "2018-02-09", oldvalue: 1.5},
  3: {gameScore: "5", reportDate: "2018-01-09", oldvalue: 1.5},
  4: {gameScore: "6", reportDate: "2018-02-09", oldvalue: 1.5}
};

// This is what I have tried:
const formatted_data = _(competitions)
  .groupBy('oldvalue')
  .map((v) => ({
      newValue: _.sumBy(v, 'oldvalue')
  }))
  .value();

console.log(formatted_data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>

With the result coming out as:

formatted_data = {
  0: {newValue: 2},
  1: {newValue: 1},
  2: {newValue: 1.5},
  3: {newValue: 1.5},
  4: {newValue: 1.5}
}

Its remapped the oldvalue to newVale but was hoping for one result all added together.

Ultimately I need formatted_data = 7.5

Any help would be awesome.


Solution

  • Convert to array using _.values() (or the native Object.values()), and then use _.sumBy().

    Note: competitions should be an array, since they have numerical keys anyway.

    const competitions = {
      0: {gameScore: "2", reportDate: "2018-05-09", oldvalue: 2},
      1: {gameScore: "3", reportDate: "2018-01-09", oldvalue: 1},
      2: {gameScore: "4", reportDate: "2018-02-09", oldvalue: 1.5},
      3: {gameScore: "5", reportDate: "2018-01-09", oldvalue: 1.5},
      4: {gameScore: "6", reportDate: "2018-02-09", oldvalue: 1.5}
    }
    
    const result = _.sumBy(_.values(competitions), 'oldvalue');
    
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>