-1

I've got an array of objects:

let recipe = [
  {
    Type:"AAAA",
    Total: 20
  },
  {
    Type:"BBBB",
    Total: 20,
  },
  {
    Type:"BBBB",
    Total: 20,
  },
  {
    Type:"AAAA",
    Total: 20,
  },
  {
    Type:"AAAA",
    Total: 20,
  }
]

And I want to get, using javascript (no libraries), the final form like this:

let finalRecipe = [["AAAA",60],["BBBB",40]]

I tried to used this but not working

let recipeModified = recipe.reduce((r, timeoff) => {
  const { Type, Total } = timeoff;
  const totalSum = Object.values({
    Total,
  }).reduce((acc, val) => ([...acc, ...val], []));

  r[Type] = [...(r[Type] || []), totalSum];

  return r;
}, {}) 

https://codesandbox.io/s/cranky-ishizaka-i7m6v?file=/src/index.js

Dazzy
  • 61
  • 2
  • 10
  • Use `array.reduce()` method for that purpose – Daniyal Lukmanov Aug 31 '20 at 08:58
  • 1
    Invalid desired output, did you mean an array of arrays? – Ele Aug 31 '20 at 08:59
  • Welcome to Stack Overflow! The way SO works, your whole question (including any necessary code) has to be **in** your question, not just linked. Two reasons: People shouldn't have to go off-site to help you; and links rot, making the question and its answers useless to people in the future. Please put a [mcve] **in** the question. More: [*How do I ask a good question?*](/help/how-to-ask) and [*Something in my web site or project doesn't work. Can I just paste a link to it?*](https://meta.stackoverflow.com/questions/254428/) – T.J. Crowder Aug 31 '20 at 08:59
  • @Daniyal Lukmanov I tried but I can't figure it out how to make it work – Dazzy Aug 31 '20 at 09:04
  • @Ele, yes, sorry, I edited my question. – Dazzy Aug 31 '20 at 09:04
  • This question has been asked so many times before... A little bit of research would be welcome. – trincot Aug 31 '20 at 09:04

1 Answers1

1

You can use the function Array.prototype.reduce for grouping the objects by Type and the function Object.values to extract the grouped objects.

let recipe = [  {    Type:"AAAA",    Total: 20  },  {    Type:"BBBB",    Total: 20,  },  {    Type:"BBBB",    Total: 20,  },  {    Type:"AAAA",    Total: 20,  },  {    Type:"AAAA",    Total: 20,  }],
    result = Object.values(recipe.reduce((r, {Type, Total}) => {
      (r[Type] || (r[Type] = [Type, 0]))[1] += Total;
      return r;
    }, {}));

console.log(result);
Ele
  • 33,468
  • 7
  • 37
  • 75