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

371
Visualizações
How to groupBy with sum using lodash

I have productId which is an array of values.

const groupByvalue= [1, 2];

I have products that have multiple product arrays.

const products = [
  {
    id: 1,
    name: 'milk',
    qty: 2
  },
  {
    id: 2,
    name: 'butter',
    qty: 2
  },
  {
    id: 3,
    name: 'milk',
    qty: 2
  },
  {
    id: 2,
    name: 'butter',
    qty: 2
  },
  {
    id: 1,
    name: 'milk',
    qty: 2
  },
  {
    id: 3,
    name: 'butter',
    qty: 2
  },
  {
    id: 1,
    name: 'milk',
    qty: 2
  },
  {
    id: 3,
    name: 'butter',
    qty: 2
  }
];

const groupByKey = 'id';

I need to group the products based on the product's id.

conditions

i)groupBy should be based on the groupByvalue with groupBykey array (only groupBy 1 , 2) ii) after the group it should sum all the qty

expected

[
  {
    id: 1,
    name : "milk", 
    qty : sum of all qty
  },
  {
    id: 2,
    name : "butter", 
    qty : sum of all qty
  }
];

Thanks!!

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

0

Using Lodash

var _ = require('lodash');

var groupByValue = [1, 2];
var groupByKey   = 'id';

const products = [
    { id: 1, name: 'milk', qty: 2 },
    { id: 2, name: 'butter', qty: 2 },
    { id: 3, name: 'milk', qty: 2 },
    { id: 2, name: 'butter', qty: 2 },
    { id: 1, name: 'milk', qty: 2 },
    { id: 3, name: 'butter', qty: 2 },
    { id: 1, name: 'milk', qty: 2 },
    { id: 3, name: 'butter', qty: 2 }
]
           
const ans = _(products)
  .groupBy(groupByKey)
  .map((product) => {
        if(groupByValue.includes(product[0].id)){
            return {
                id: product[0].id,
                name: product[0].name,
                qty: _.sumBy(product, 'qty')
            }
        }
    })
  .value()

console.log(ans.filter(item => item));

Output :-

[ { id: 1, name: 'milk', qty: 6 }, { id: 2, name: 'butter', qty: 4 } ]
about 4 years ago · Juan Pablo Isaza Relatório

0

No need for lodash whatsoever, this is a native .reduce() task. You may do like;

var groupByValue = [1, 2],
    groupByKey   = 'id',
    products     = [ { id  : 1
                     , name: 'milk'
                     , qty : 2
                     }
                   , { id  : 2
                     , name: 'butter'
                     , qty : 2
                     }
                   , { id  : 3
                     , name: 'milk'
                     , qty: 2
                     }
                   , { id  : 2
                     , name: 'butter'
                     , qty : 2
                     }
                   , { id  : 1
                     , name: 'milk'
                     , qty : 2
                     }
                   , { id  : 3
                     , name: 'butter'
                     , qty : 2
                     }
                   , { id  : 1
                     , name: 'milk'
                     , qty : 2
                     }
                   , { id  : 3
                     , name: 'butter'
                     , qty : 2
                     }
                   ],
  interim        = products.reduce( (r,p) => ( groupByValue.includes(p[groupByKey]) && (r[p[groupByKey]] ? r[p[groupByKey]].qty += p.qty
                                                                                                         : r[p[groupByKey]] = Object.assign({},p))
                                             , r
                                             )
                                  , {}
                                  ),
  result         = Object.values(interim);
  console.log(result);

The milk products with id:3 doesn't count.

about 4 years ago · Juan Pablo Isaza Relatório

0

I would filter the array first, and then make the map, this can be done in single .reduce(...) function, but its more readable using lodash:

const _ = require('lodash');
const groupByValue = [1, 2];
const groupByKey = 'id';

 const products = [
    { id: 1, name: 'milk',  qty:  1 },
    { id: 2, name: 'butter', qty: 2 },
    { id: 3, name: 'cheese',  qty: 4 },
    { id: 2, name: 'butter', qty: 5 },
    { id: 1, name: 'milk',  qty: 3 },
    { id: 3, name: 'cheese', qty: 6 },
    { id: 1, name: 'milk',  qty: 1 },
    { id: 3, name: 'cheese', qty: 7 }
];

const result = _(products)
       .filter(itm => groupByValue.includes(itm.id))
       .groupBy(groupByKey)
       .map(arr => {
           const { id, name } = arr[0];

           return { id, name, qty: _(arr).sumBy('qty') };
       })
       .value();

console.log(result);

// output: [{ id: 1, name: 'milk', qty: 5},{id: 2, name: 'butter', qty: 7}]

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