How to determine if object is in array

I need to determine if an object already exists in an array in javascript.

eg (dummycode):

var carBrands = [];

var car1 = {name:'ford'};
var car2 = {name:'lexus'};
var car3 = {name:'maserati'};
var car4 = {name:'ford'};

carBrands.push(car1);
carBrands.push(car2);
carBrands.push(car3);
carBrands.push(car4);

now the “carBrands” array contains all instances.
I’m now looking a fast solution to check if an instance of car1, car2, car3 or car4 is already in the carBrands array.

eg:

var contains =  carBrands.Contains(car1); //<--- returns bool.

car1 and car4 contain the same data but are different instances they should be tested as not equal.

Do I have add something like a hash to the objects on creation? Or is there a faster way to do this in Javascript.

I am looking for the fastest solution here, if dirty, so it has to be 😉 In my app it has to deal with around 10000 instances.

no jquery

14 Answers
14

Leave a Comment