Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if value exists in this JavaScript array?

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?

like image 968
Oseer Avatar asked Oct 12 '11 12:10

Oseer


People also ask

How do you check if a value exists in an array?

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.

How do you check if value exists in array react?

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.

How do you check if a value is present in an object in JavaScript?

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 .


2 Answers

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);
like image 110
Manuel van Rijn Avatar answered Sep 19 '22 04:09

Manuel van Rijn


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;
}
like image 32
gion_13 Avatar answered Sep 18 '22 04:09

gion_13