0

I am new to JavaScript and i will appreciate some help . I try to search array for element but i cant find the right solution . First i tried this , but no success.

 var find = function(string, array) {
   for(i=0;i>=array.length-1;i++){
     if(array[i]==string){
       return true;
      }
     else{
       return false;
       }
      }
  };

Then i tried this

var find = function(string, array) {
  if(array.indexOf(string)>-1){
      return true;}
    else{
      return false;
        }

  };

but it doesn't work with numbers This are my tests

Test.assertEquals(find("hello", ["bye bye","hello"]), true);
Test.assertEquals(find("2", ["bye bye","2"]), true);
Test.assertEquals(find("2", ["bye bye",2]), false);
DQQM_
  • 1

3 Answers3

1

You are returning false the first time an element is found that doesn't match what you are looking for. You should only return false once the entire array has been processed. Your loop is also incorrect, if i is 0, it will never be greater than or equal to the array length unless the array is empty:

 var find = function(string, array) {
   for(i=0; i < array.length; i++) {
     if(array[i]==string) {
       return true;
     }
   }
   return false;
 };

You should also focus on naming conventions. Your function is called find, but it doesn't actually return the found element. I would name the function contains.

This is a good learning exercise, but don't reinvent the wheel:

[1,2,3,4,5,6].indexOf(foo) > -1

This will return true if foo is in the array.

Brennan
  • 5,632
  • 2
  • 17
  • 24
0

Assuming you have a Test.assetEquals Function just use the build in array function:

Test.assertEquals((["bye bye","hello"].indexOf('hello') > -1),true);
nril
  • 558
  • 2
  • 7
0

With type conversion:

var a = [1, 2, 3];
if (a.some(function (x) { return x == "2" })) {
    ...
}

Strict comparison:

if (a.indexOf("2") >= 0) {
    ...
}
Artem
  • 1,773
  • 12
  • 30