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?
The simplest and fastest way to check if an item is present in an array is by using the Array. indexOf() method. This method searches the array for the given item and returns its index. If no item is found, it returns -1.
To check if an element exists in an array in React: Use the includes() method to check if a primitive exists in an array. Use the some() method to check if an object exists in an array.
JavaScript provides you with three common ways to check if a property exists in an object: Use the hasOwnProperty() method. Use the in operator. Compare property with undefined .
Something like this:
function in_array(array, id) {
for(var i=0;i<array.length;i++) {
return (array[i][0].id === id)
}
return false;
}
var result = in_array(ArrayofPeople, 235);
You should iterate over the array and manually check if you have a matching id:
function getPersonById(id){
for(var i=0,l=ArrayofPeople.length;i<l;i++)
if(ArrayofPeople[i][0].id == id)
return ArrayofPeople[i];
return null;
}
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:
ArrayofPeople = {};
ArrayofPeople[529] = {"id": "529", "name": "Bob"};
ArrayofPeople[820] = {"id": "820", "name": "Dave"};
ArrayofPeople[235] = {"id": "235", "name": "John"};
function getPersonById(id){
return id in ArrayofPeople
? ArrayofPeople[id]
: null;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With