Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

377
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!