0

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!")
                };
            };
WebAhmed
  • 3
  • 4
  • possible duplicate of ["concat" does not join JavaScript arrays together?](http://stackoverflow.com/questions/12810366/concat-does-not-join-javascript-arrays-together) – Qantas 94 Heavy Oct 19 '14 at 05:55

1 Answers1

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);
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • "Because .push() can take more than one argument." -- whaaaaaat! You learn something new every week! – Rudie Oct 19 '14 at 02:16
  • Thank you very much! I was trying to use `concat()` thinking it functioned similarly to `push()` but your explanation was pretty clear. – WebAhmed Oct 19 '14 at 06:00