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/

8
  • I'm not understanding your question, I might be reading it wrong but in short terms are you asking how to check for duplicates? Commented Nov 17, 2017 at 3:37
  • If you are looking to remove duplicates then maybe this JsFiddle Demo will be of some help. All credit to this answer- "Remove duplicates in an object array Javascript" Commented Nov 17, 2017 at 4:03
  • Reduce is not the correct method. Read up on it on MDN Commented Nov 17, 2017 at 4: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. Commented Nov 17, 2017 at 4: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. Commented Nov 17, 2017 at 4:20

0

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.