-1

I'm not really sure why my code isn't running correctly.. what I'm trying to do is create a grocery list object that has a couple of functions to add and remove items.. I can instantiate the objects with new items but my functions don't seem to work for some reason. If you could save me the few hairs left in my head and tell me where the issue is I would greatly appreciate it.

            var groceryList = function(itemNames,quantity) {
                if (Array.isArray(itemNames)) {
                    this.items = itemNames;
                    this.quantity = quantity

                    this.addItems = function(newItems){
                        if ( Array.isArray(newItems) ) {
                            this.items.concat(newItems);
                        }   else {
                            console.log("Please enter the items in an array fashion!");
                        };
                    };

                    this.removeItem = function(name) {
                        var listSize = this.items.length;
                        for (var i = 0; i < listSize; i++) {
                            if (this.items[i] == name) {
                                this.items.splice(i,1);
                                break;
                            } else {
                            console.log("Please enter the items in an array fashion!")
                            };
                        };
                    };
                } else {
                    console.log("Please enter the items in an array fashion!")
                };
            };
2

1 Answer 1

1

.concat() returns a new array so you have to assign the result back to your instance variable.

So this:

this.items.concat(newItems);

needs to be changed to this:

this.items = this.items.concat(newItems);

or, you could actually use this to append to the array directly:

this.items.push.apply(this.items, newItems);

Because .push() can take more than one argument.


Then, in your .removeItem() function, you need to remove the item you actually found by changing this:

this.items.splice(2,1);

to this:

this.items.splice(i,1);
Sign up to request clarification or add additional context in comments.

2 Comments

"Because .push() can take more than one argument." -- whaaaaaat! You learn something new every week!
Thank you very much! I was trying to use concat() thinking it functioned similarly to push() but your explanation was pretty clear.

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.