-1

I'm working with an array of objects that looks something like this:

const fruits = [
 {
   Fruit: Apple,
   Count: 4
 },
 {
   Fruit: Orange,
   Count: 3
 },
 {
   Fruit: Apple,
   Count: 2
 }
]

I like to end up with my array looking something like this:

const fruits = [
 {
  Fruit: Apple,
  Count: 6
 },
 {
  Fruit: Orange,
  Count: 3
 },
]

Is there any help with this? I've tried to use Reduce but Reduce, needless to say, is my biggest weakness in JavaScript. I've looked at so many articles that get a close answer but nothing that can fully help me. Thank you for the help.

ravenUSMC
  • 495
  • 5
  • 23
  • 2
    _"...but nothing that can fully help me"_ - There are hundreds of questions on how to group an array of objects. Add your approach and add an explanation which part of it doesn't work and why you think so. Imho, this will help you more than just another ready-to-use answer. – Andreas May 28 '20 at 15:36

2 Answers2

1

Here's the reduce solution you need:

const fruits = [
 {
   Fruit: "Apple",
   Count: 4
 },
 {
   Fruit: "Orange",
   Count: 3
 },
 {
   Fruit: "Apple",
   Count: 2
 }
]

let result = fruits.reduce((acc,current) => {
   let obj = acc.find(x => x.Fruit === current.Fruit);
   if(!obj){
      acc.push({ Fruit: current.Fruit, Count: current.Count });
   } else {
      obj.Count += current.Count;
   }
   return acc;
}, []);

console.log(result);

Basically you need to build a new array (acc) and add a new item if there's no such Fruit or increment the counter.

mickl
  • 48,568
  • 9
  • 60
  • 89
0

const fruits = [{
    Fruit: "Apple",
    Count: 4
  },
  {
    Fruit: "Orange",
    Count: 3
  },
  {
    Fruit: "Apple",
    Count: 2
  }
];

// c => current value
// n => next value
const asObject = fruits.reduce((c, n) => ({ ...c,
  [n.Fruit]: (c[n.Fruit] || 0) + n.Count
}), {});

const result = Object.entries(asObject).map(([k, v]) => ({
  Fruit: k,
  Count: v
}));

console.log(asObject);
console.log(result);
Vanojx1
  • 5,574
  • 2
  • 23
  • 37