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

149
Visualizações
Group and sum array of obects using Lodash

How to group an array of objects using object value, and then sum the column values of grouped objects. this is the sample object.

let salesData = [
   {
       'phone': 'iPhone',
       'city': 'NewYork',
       '01/09': 200,
       '02/09': '',
       '03/09': 120,
       '04/09': ''

   },
   {
       'phone': 'iPhone',
       'city': 'Los Angels',
       '01/09': 80,
       '02/09': 140,
       '03/09': '',
       '04/09': 15
   },
   {
        'phone': 'Samsung',
        'city': 'New York',
        '01/09': '',
        '02/09': 70,
        '03/09': 10
        '04/09': 20
   }
],
dynamicKeys = ['01/09', '02/09', '03/09'];

Here i need to group the data with city and sum the values of dynamicKeys, like this

[
   {
     'city': 'New York',
     '01/09': 200,
     '02/09': 70,
     '03/09': 130
   },
   {
     'city': 'Los Angels',
     '01/09': 80,
     '02/09': 140,
     '03/09': ''
 
   }
]

this is the code i tried, but its not working

let newArr = salesData.reduce((acc, item) => {
   let existItem = acc.find(d => 
      item.city === d.city
   )
   if(existItem){
     dynamicKeys.forEach(d => {
        if(!isNaN(item[d])) existItem[d] += item[d]
     })
   }else{
     acc.push(item);
   }
   return acc
},[])

here the grouping seems to be working, but the sum of dynamicKeys is not correct, what is the best way to achieve this using loadsh / plain js

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

We can create the desired structure using Array.reduce(), we create an object with properties for each city name, then properties for each sales date in dynamic keys.

Once we have built this object, we can use Object.values() to get the data as an array:

const salesData = [ { 'phone': 'iPhone', 'city': 'New York', '01/09': 200, '02/09': '', '03/09': 120, '04/09': ''  }, { 'phone': 'iPhone', 'city': 'Los Angeles', '01/09': 80, '02/09': 140, '03/09': '', '04/09': 15 }, { 'phone': 'Samsung', 'city': 'New York', '01/09': '', '02/09': 70, '03/09': 10, '04/09': 20 } ]; 
const dynamicKeys = ['01/09', '02/09', '03/09'];

const result = Object.values(salesData.reduce((acc, salesItem) => { 
    return dynamicKeys.reduce((acc, key) => {
       acc[salesItem.city] = acc[salesItem.city] || { city: salesItem.city }; 
       acc[salesItem.city][key] = (+acc[salesItem.city][key] || 0) + (+salesItem[key] || 0);
       return acc;
    }, acc);
}, {}))

console.log('Sales data:', result)

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