0

This is my code :

var array = 
  [
    {
      id: "BG",
      qty: 100
    }, 
    {
      id: "BG",
      qty: 35
    }, 
    {
      id: "JP",
      qty: 75
    },
    {
      id: "JP",
      qty: 50
    }
 ];


var result = array.reduce((obj, cur) => (obj[cur.id] = [...(obj[cur.id] || []), cur], obj), {})
console.log(result);

What I would like to do is group the array into sub arrays based on the ID's which the array.reduce does. But now I want to sum the total of the qty.

So I'm expecting values the total qty for BG to be = 35 and the total qty for JP to be 125, and then I want to be able to run math conditions on those numbers

1
  • 2
    Could you not have used the information you received from the question you asked an hour ago to decipher the solution? Commented Nov 15, 2022 at 23:00

1 Answer 1

1

It really have been asked before, but by the time I'd search for it I could also write it. It's not that long.

var array = [{
    id: "BG",
    qty: 100
  },
  {
    id: "BG",
    qty: 35
  },
  {
    id: "JP",
    qty: 75
  },
  {
    id: "JP",
    qty: 50
  }
];

var result = Object.values(array.reduce(function(agg, item) {
  agg[item.id] = agg[item.id] || {
    id: item.id,
    qty: 0
  }
  agg[item.id].qty += item.qty;
  return agg;
}, {}));

console.log(result);

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.