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
carBrands, and then just testing on the keys you want.===will only work in the simplest case where you have exact references to the objects in the array.includeswith objects have been addressed in How do I check if an array includes a value in JavaScript? multiple times. Some of the answers here don’t even consider this caveat. I don’t see a reason why this shouldn’t be closed as a duplicate. It does more harm than good to separate these questions by use case and leave the object reference caveat entirely unaddressed by one question, just because it doesn’t explicitly ask about object references.