html - In Javascript without jQuery, I am to find if any value in one array exists in a separate array -


i trying determine if value 1 array matches value array. problem having if there 2 values in array , first value found second not found, indicator coming false when need return true. here example code i'm working with:

var itemarray = ['apples','bananas','cherries']; var categoryarray = ['donuts','cherries','eclairs','fruit','grapes'];  for(var z=0; z<itemarray.length; z++){   for(var y=0; y<categoryarray.length; y++){     if(itemarray[z] == categoryarray[y]) var isinarray = true;     else var isinarray = false;   } }  alert(isinarray); 

appreciate help, let me know if more information needed.

you need break or return once you've found value matches. otherwise, else case overwrites isinarray if true. alternately, initialize isinarray false, , only assign true in loop. here's how i'd it:

function isinarray(itemarray, categoryarray) {     for(var z=0; z<itemarray.length; z++) {       for(var y=0; y<categoryarray.length; y++) {         if(itemarray[z] == categoryarray[y]) return true;       }     }      return false; } 

i prefer return in cases such this.


Comments