搜索数组,按查询相关性显示结果

时间:2021-03-25 08:34:04

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:

我想在javascript数组中执行搜索,该数组显示与查询相关的所有结果,类似于以下SQL语句:

"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:

假设我的查询字符串是“ap”,它将按以下顺序返回结果:

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?

这可能在JavaScript中?怎么样?

2 个解决方案

#1


1  

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 

#2


1  

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

这是未经测试的,就在我的头顶。但是你应该在resultArray中找到你想要的结果

#1


1  

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 

#2


1  

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

这是未经测试的,就在我的头顶。但是你应该在resultArray中找到你想要的结果