0

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.

1
  • Can you a add a fiddle link. People will be able to help you more easily. Commented Jul 15, 2015 at 11:38

5 Answers 5

3

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(); 
Sign up to request clarification or add additional context in comments.

Comments

2

You can use indexOf, like this:

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

Comments

1

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
})();

4 Comments

I think every fits better: activeIds.every(function(v){return v != uid}).
Just to make sure it works even if the browsers don't support ES6 feature. I'm not sure if activeIds.some(function(n){ return n===uid }) would produce better performance. Just wondering if it breaks as soon as it hits a truthy case.
I thought too much BTW. Elements are just primitive numbers. :)
filter and every are ES5 features. Only IE8 needs a shim…
1

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

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.