Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

79
Views
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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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/lodash@4.17.21/lodash.min.js"></script>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!