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

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

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 Denunciar

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 Denunciar

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