PeterInvincible
PeterInvincible

Reputation: 2310

Search an array, display results by relevance to query

I'd like to perform a search in a javascript array, that displays all results in relevance to the query, something equivalent to the following SQL statement:

"SELECT * FROM table WHERE column LIKE input"

Here's an example:

var array = [];
array[0] = "Apple";
array[1] = "Apricot";
array[2] = "Pear";
array[3] = "Peacock";

Let's say my querystring is "ap", it would return results in the following order:

1. "Apple"
2. "Apricot"

query = "p"
result:

1. "Pear"
2. "Peacock"
3. "Apple"
4. "Apricot"

query = "r"
result:

1. "Apricot"
2. "Pear"

Is this possible in javascript? How?

Upvotes: 0

Views: 1149

Answers (2)

RonnyKnoxville
RonnyKnoxville

Reputation: 6404

var array = [];
array[0] = "Apple";
array[1] = "Apricot";
array[2] = "Pear";
array[3] = "Peacock";

function searchArray(query){
    resultArray = [];
    for(var i=0;i<query.length-1;i++){
        var char = query.charAt(i);
        if(array[i].indexOf(char)!=null){
            resultArray.push(array[i]);
        }
    }
    return resultArray;
}

This is untested, just off the top of my head. But you should have the result you are looking for in resultArray

Upvotes: 1

Anand Jha
Anand Jha

Reputation: 10724

Try this,

    var arr = [];
    arr[0] = "Apple";
    arr[1] = "Apricot";
    arr[2] = "Pear";
    arr[3] = "Peacock";

    var resultArr=[];
    var str='ap'//string to search

    for(var i=0;i<arr.length;i++){
      if(arr[i].indexOf(str) != -1){
         resultArr.push(arr[i]);
      }
    }

  alert('search results:'+resultArr);
    //resultArr contains reults 

Upvotes: 1

Related Questions