-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.

1
  • 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. Commented May 28, 2020 at 15:36

2 Answers 2

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.

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

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.