简体   繁体   中英

Check if value exists in an object in array of objects

I am trying to write the code of following algorithm

  • I have an array of active_id (array)
  • ID coming from url (string)
  • if value of ID does not exist in active_id array
    • run the function A()
  • else do nothing.

Note - function A() should be run only once.

I tried writing the code

for (var i = 0; i < activeIds.length; i++) {
    if (activeIds[i] != uid) {
         A();  //This is running multiple times.
    }

I tried using while loop

var i = 0;
while (activeIds[i] != uid) {
     A();  //This is running multiple times again.
    i++;
}

There is something i am missing. not able to figure it out.

You can just use indexOf function which will return -1 if element is not exist on array and positive number start 0 till array (length -1) if element exist:

if (activeIds.indexOf(uid) == -1) {
    A();  
}

function A(); 

您可以使用indexOf ,如下所示:

if( activeIds.indexOf(id) < 0 ) A();

If you want to invoke function A() only if the a particular ID ( uid ) does not exist in your array activeIds , you may want to alter your loop approach with this:

if (activeIds.filter(function(n){ return n===uid }).length==0){
    A();
}

Where you have a definition of function A() ready to use already.

Side note You syntax with function A(){} is just defining the function A but it's not going to run it. If you want to define and run it once, you may do:

(function A(){
   // logic goes here
})();

You can use array.indexof() function in order to find the value. It will look something like that:

if(activeIds.indexOf(uid) === -1){
    A();
}

Try this, code.

var i=0;
var isMatchFound = false;

while (activeIds.length >= i) {
  if(activeIds[i] ==uid){
    isMatchFound = true;
    break;
}
 i++;
}

if(isMatchFound){
   //Call Function A
    A();
}

Hope this will help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM