Alex Nicholson
Alex Nicholson

Reputation: 63

Adding an object to an array only if that object does not already exist in the array

I am trying to make an inventory system where when an item is obtained it will only put the item into the array if it does not already exist in the array. Then regardless of whether it was put into the array or not, find the item in the array and increase its amount by 1. This is what I have at the moment:

function newItem(){
    apple = new uniqueItem("apple", "resources/apple.png")

    if (inventory.indexOf(apple) != null){
        inventory.push(apple)
    }
    inventory[inventory.indexOf(apple)].amount += 1
}

Im still pretty new to javascript and I would appreciate it if someone could point me in the right direction

Upvotes: 1

Views: 105

Answers (4)

Redu
Redu

Reputation: 26161

There is this Array.prototype.includes() method at your service just for this job.

var o1 = {a:1,b:2},
   arr = [];
arr.push(o1);
arr.includes(o1); // <- true so don't add again

For more on this check Array.prototype.includes() out.

Upvotes: 1

mramiruladly
mramiruladly

Reputation: 9

I think this may help you too

    <p> Year : <select style="width: 150px;">
        <option value ="2014">2014</option>
        <option value ="2015">2015</option>
        <option value =" '2015">2015</option>

    </select>
    </p>

    <input  type="submit" value="Submit">
            <input type="submit" value="cancel">

</center>
</body>

Upvotes: 0

Luke P. Issac
Luke P. Issac

Reputation: 1591

You should not use indexOf here. Use something like below which iterates over the array and compares with each object in it. indexOf takes a string as value rather than a object.

function containsObject(obj, list) {
   var i;
   for (i = 0; i < list.length; i++) { 
     if (list[i] === obj) { return true; } 
   } 
   return false;
 }

Upvotes: 0

Imran
Imran

Reputation: 4750

You can do it by your own! Just loop through all inventory and check whether the item you are trying to insert is already exist. If it doesn't exist then insert it.

Upvotes: 0

Related Questions