Check if Obj is in Array then run code if not

76 Views Asked by At

I am trying to check if an object is within an array, I have managed to do this however I am unable to run the code within the blocks. Here is the code snippet:

basket.add = function(item) {
    for(var i = 0; i < this.items.length; i++){
        if(item === this.items[i]){
            basket.items[i].count += 1;
        }else{
            basket.items.push(item);  
        };
    };
    basket.print();
};

When I run the code without the if statement it works fine apart from the fact it push the obj again. When I check and then push the obj if it is not in the array this code does not work.

2

There are 2 best solutions below

1
On BEST ANSWER

Your current code loops through items, pushing another reference to item to the end of the array each time it finds a value in items that doesn't match item. I don't think this is what you want.

Instead you can use

basket.add = function(item) {
    var i = basket.items.indexOf(item);
    if (i == -1) {
        basket.items.push(item);
    }
    else {
        basket.items[i].count += 1;
    }
};        

For users of IE8 and earlier .indexOf won't work, so if that's important you can add this polyfill.

2
On

You're looping over your items trying to determine if the item being added is already in the "basket":

for(var i = 0; i < this.items.length; i++){
    if(item === this.items[i]){
       ....

Im guessing you dont want to add the item once for each item in the array already! So move the adding of a new item outside the loop.

Another problem is that you are checking the length of this.items but then pushing to basket.items - this may be valid but I suspect not.

basket.add = function(item) {
    var foundItem = false;
    for(var i = 0; i < this.items.length; i++){
        if(item === this.items[i]){
            this.items[i].count += 1;
            foundItem = true;
            break;
        }
    };
    if(!foundItem){
         this.items.push(item);
    }
    basket.print();
};