Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

80
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda