Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

87
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda