3

The idea is this..

var myArray = ['Apple juice','Banana Milkshake','Some Treat'];
function search(search_term){
if(myArray.indexOf(search_term) != -1){
     return ..... //this is what i want to do.
};

// code is run as.
search("Apple");

My thought is when i call the search() function and it finds a value, it should return the full length or the full value of the matched term so if i do search("Apple"); it should return 'Apple Juice' but i don't know any way to do this so can anyone help me find a way to do this?

Scimonster
  • 32,893
  • 9
  • 77
  • 89
Adarsh Hegde
  • 623
  • 2
  • 7
  • 19

2 Answers2

2

You can do the following:

for (var i in myArray)
    if (myArray[i].indexOf(search_term) != -1)
        return myArray[i];

Or if you want to return all matches in an array:

myArray.filter(function(item) {
    return item.indexOf(search_term) != -1;
}); 
JuniorCompressor
  • 19,631
  • 4
  • 30
  • 57
1

Maybe something like that ?

   var myArray = ['Apple juice','Banana Milkshake','Some Treat', 'Here'];

    function search(search_term){
        for(var i=0; i < myArray.length; i++) {

            if(myArray[i].indexOf(search_term) !== -1) {
                return myArray[i];
            }
        }

        return false;
    };

    // code is run as.
    alert(search("Here"));
Mouloud
  • 3,715
  • 1
  • 26
  • 20