50

I would like to group an array of objects by Id and sum the quantity in jQuery. How can I achieve this?

For example:

var array = [
  { Id: "001", qty: 1 },
  { Id: "002", qty: 2 },
  { Id: "001", qty: 2 },
  { Id: "003", qty: 4 }
]

Should result in:

[
  { Id: "001", qty: 3 },
  { Id: "002", qty: 2 },
  { Id: "003", qty: 4 }
]
1
  • An updated, TypeScript-friendly SO that also supports multiple grouping keys is discussed here Commented May 23, 2023 at 17:10

2 Answers 2

125

You can loop and sum it up (reduce documentation)

var array = [
  { Id: "001", qty: 1 }, 
  { Id: "002", qty: 2 }, 
  { Id: "001", qty: 2 }, 
  { Id: "003", qty: 4 }
];

var result = [];
array.reduce(function(res, value) {
  if (!res[value.Id]) {
    res[value.Id] = { Id: value.Id, qty: 0 };
    result.push(res[value.Id])
  }
  res[value.Id].qty += value.qty;
  return res;
}, {});

console.log(result)

Fiddle: Fiddle

Sign up to request clarification or add additional context in comments.

3 Comments

setting qty to 0 is important in the res[value.Id] = { qty: 0, Id: value.Id}; step. Otherwise u get duplicate values
Should this not be var result = array.reduce.... instead of using a sideeffect?
I believe this only work because the Id is numeric cause the Index of the array cannot be a string...
1
var newArr = [];

$.each(array,function(index,element){
    if(newArr[element.Id]==undefined){
        newArr[element.Id] =0;
    }
    newArr[element.Id] += element.qty;
});
console.log(newArr);

Demo

2 Comments

You are not creating an array of objects
This uses element.id as an array index, not as an object key.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.