0

I'm new to javascript, and I'm trying to learn more about working with array's so I built a grocery list builder, and I'm getting stuck on reducing the list if the user accidentally inserts an item twice.

I think the problem is that my reducing function isn't hitting the item selector, but I haven't been able to find any examples showing this kind of problem.

This is what I have for a reducing function:

function reducingFood() {
   var reducedFood = myGroceries.reduce(function(obj, item) {
   var itemName = item['item'];
       if(!obj[itemName]) {
           obj[itemName] = 0;
       }
       obj[itemName]++;
       return obj;

   }, {}) 

    addStructure();
}

I setup a JSFiddle showing the full code: https://jsfiddle.net/Jon43/frvLc7Le/8/

Jon
  • 13
  • 2
  • I'm not understanding your question, I might be reading it wrong but in short terms are you asking how to check for duplicates? – NewToJS Nov 17 '17 at 03:37
  • If you are looking to remove duplicates then maybe this [**JsFiddle Demo**](https://jsfiddle.net/bhxvrbzz/) will be of some help. [**All credit to this answer- "Remove duplicates in an object array Javascript"**](https://stackoverflow.com/questions/36032179/remove-duplicates-in-an-object-array-javascript#answer-36032432) – NewToJS Nov 17 '17 at 04:03
  • Reduce is not the correct method. Read up on it on MDN – Andrew Nov 17 '17 at 04:06
  • @Andrew Well it seems to work just fine in the example I have provided from an existing answer. I thought I would see if this has been answered before rather than answering and possibly creating a duplicate answer. What is the correct method **Andrew**, could you give an example please. I can no doubt take note from it for future. Thank you. – NewToJS Nov 17 '17 at 04:09
  • @NewToJS You're right. I misread part of the code. IMO, this type of question is most straightforward with a full algorithm, but this works too. My bad. – Andrew Nov 17 '17 at 04:20
  • @Andrew No problem, we all misread things from time to time. I thought you had a better method which is always useful to learn hence me asking for a demo. – NewToJS Nov 17 '17 at 04:42
  • @NewToJS https://jsfiddle.net/fe27mooL/1/ I use a set to inherently remove duplicates and then rebuild the object. I love ES6. – Andrew Nov 17 '17 at 04:48
  • Appreciate the guidance. Tried both, and they work great. More than one way to do things is suppose. I'll read up on this on MDN. – Jon Nov 17 '17 at 14:15

0 Answers0