Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading