Search code examples
javascriptlodash

Lodash - perform calculation on an array of objects


I am struggling with finding the right lodash function, if you could help, that’d be great.

I have an array of:

   [
      { '2002': 2, '2003': 1, '2004': 5 },
      { '2002': 2, '2003': 5, '2004': 2 },
      { '2002': 3, '2003': 2, '2004': 3 },
      { '2002': 5, '2003': 4, '2004': 4 }
    ]

As there are 4 different inputs as below:

[input1, input2, input3, input4]

For each year I want to perform the following:

(input1 + input2 - input3) / input4

In the year 2002, the output: (2 + 2 - 3) / 5 = 0.2

Is there a lodash helper function to output:

[ [ 2002, 0.2 ], [ 2003, 1 ], [ 2004, 1 ] ] 

Thank you in advance


Solution

  • You can do this very directly with vanilla javascript by mapping over the Object.keys of the first object in the array and then using each key to access the relevant properties from each object in the array and perform your calculation on them.

    const input = [
      { '2002': 2, '2003': 1, '2004': 5 },
      { '2002': 2, '2003': 5, '2004': 2 },
      { '2002': 3, '2003': 2, '2004': 3 },
      { '2002': 5, '2003': 4, '2004': 4 }
    ]
    
    const calc = ([a, b, c, d]) => (a + b - c) / d;
    
    const result = Object.keys(input[0]).map(k => [k, calc(input.map(o => o[k]))])
    
    console.log(result)

    A possible sequence with lodash...

    const input = [
      { '2002': 2, '2003': 1, '2004': 5 },
      { '2002': 2, '2003': 5, '2004': 2 },
      { '2002': 3, '2003': 2, '2004': 3 },
      { '2002': 5, '2003': 4, '2004': 4 }
    ];
    
    const result = _.chain(
      _.mergeWith(...input, (a, b) => [].concat(a, b))
    )
      .mapValues(([a, b, c, d]) => (a + b - c) / d)
      .toPairs()
      .value();
    
    console.log(result);
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>