I have a JavaScript array, where each new item added to the array gets the next incremental number. An example would be as follows (I hope Im writing this correctly):
ArrayofPeople[0] = [{"id": "529", "name": "Bob"}];
ArrayofPeople[1] = [{"id": "820", "name": "Dave"}];
ArrayofPeople[2] = [{"id": "235", "name": "John"}];
The array is named ArrayofPeople
, storing multiple data points for each person.
I need to know if an element with id of 820 exists in the array or not. How would this be done?
Something like this:
You should iterate over the array and manually check if you have a matching id:
Of course, this is pretty inefficient. I suggest you store your objects into an associative array (a.k.a. an object) indexed by the person’s id. Then, the access to a person with a certain id is immediate since objects are nothing than hash-tables:
You can use the relatively new
Array.prototype.some()
to find whether an item exists (a shim is provided in the documentation):