How to check if value exists in this JavaScript array?
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;
}
ArrayofPeople = new Array();
ArrayofPeople[0] = [{"id": "529", "name": "Bob"}];
ArrayofPeople[1] = [{"id": "820", "name": "Dave"}];
ArrayofPeople[2] = [{"id": "235", "name": "John"}];
var str = '820';
var is_found = 'not found';
for(item in ArrayofPeople){
target = ArrayofPeople[item][0];
if(target['id'] === str)
is_found = 'found';
}
alert(is_found);
You can use the relatively new Array.prototype.some()
to find whether an item exists (a shim is provided in the documentation):
var ArrayofPeople = [];
ArrayofPeople[0] = [{"id": "529", "name": "Bob"}];
ArrayofPeople[1] = [{"id": "820", "name": "Dave"}];
ArrayofPeople[2] = [{"id": "235", "name": "John"}];
function in_array(array, id)
{
return array.some(function(item) {
return item[0].id === id;
});
}
console.log(in_array(ArrayofPeople, '820')); // true