Javascript根据最接近的匹配对数组进行匹配

时间:2019-02-11 20:47:18

标签: javascript search

我正在实现一个搜索,该搜索根据查询给出建议。它检查是否有任何建议包括查询。 但是,建议未按最接近的匹配排序。如何对它们进行排序?

这是我的代码:

this.suggestions = this.allSuggestions.filter(s => s.Subject.includes(this.query) || s.Child_Subject.includes(this.query))

1 个答案:

答案 0 :(得分:0)

我今天刚做了sweetScoreSweetSort。它伤了我的小脑。希望它对您有用,就像对我一样。

//<![CDATA[
var doc, M, I, special, unspecial, regEsc, sweetScore, SweetSort; // for use on other loads
addEventListener('load', function(){ // make sure DOM is loaded
doc = document;
M = function(tag){
  return doc.createElement(tag);
}
I = function(id){
  return doc.getElementById(id);
}
special = function(str){ // for use with .innerHTML not .value or .text
  return str.replace(/&/g, '&amp;').replace(/'/g, '&apos;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
unspecial = function(str){
  return str.replace(/&amp;/g, '&').replace(/&apos;/g, "'").replace(/&quot;/g, '"').replace(/&lt;/g, '<').replace(/&gt;/g, '>');
}
regEsc = function(string){
  return string.replace(/[.*+?^()[\]|{}\\$]/g, '\\$1');
}
sweetScore = function(string){
  for(var i=0,str=string.toLowerCase(),s=0,n=1,l=str.length; i<l; i++,n++){
    s += Math.pow(str.charCodeAt(i), n);
  }
  return s;
}
SweetSort = function(array){
  var stash;
  this.candy = function(array){
    stash = array.slice();
    return this;
  }
  if(array !== undefined)this.candy(array);
  this.sweet = function(string){
    var str = regEsc(string), score = sweetScore(str), rx = new RegExp('^'+str, 'i'), p = [], r;
    if(str !== ''){
      for(var i=0,l=stash.length; i<l; i++){
        if(stash[i].match(rx)){
          p.push(stash.splice(i, 1)[0]); i--; l--;
        }
      }
      p.sort(function(a, b){
        return a.length-b.length;
      });
    }
    stash.sort(function(a, b){
      return Math.abs(score-sweetScore(a))-Math.abs(score-sweetScore(b));
    });
    r = p.concat(stash); stash = stash.concat(p);
    return r;
  }
}
var sweet_score_in = I('sweet_score_in'), sweet_sort = I('sweet_score'), sweet_sort_in = I('sweet_sort_in'), sweet_sort = I('sweet_sort');
sweet_score_in.onkeyup = function(){
  sweet_score.innerHTML = sweetScore(this.value);
}
var sm = new SweetSort(['how', 'now', 'brownest', 'Brown', 'Cow']);
sweet_sort_in.onkeyup = function(){
  sweet_sort.innerHTML = special(JSON.stringify(sm.sweet(this.value.trim())));
}
sweet_sort.innerHTML = special(JSON.stringify(sm.sweet('')));
I('content').style.display = 'block'; // in case you are creating other DOM parts with JavaScript
});// end load
//]]>
/* external.css */
*{
  padding:0; margin:0; box-sizing:border-box; overflow:hidden;
}
html,body{
  width:100%; height:100%; background:#aaa; color:#000;
}
body{
  position:relative; font:22px Tahoma, Geneva, sans-serif;
}
body>*{
  position:absolute;
}
#content{
  display:none; width:100%; height:100%; 
}
.page{
  position:relative; width:100%; height:100%; float:left;
}
.bar{
   width:100%; height:38px; padding:3px; background:#ccc; color:#000;
}
h1{
  font-size:28px; margin-left:3px;
}
.main{
  height:calc(100% - 38px); padding:5px; overflow-y:auto;
}
label{
  display:block; height:26px; font-weight:bold; 
}
label>em{
  font-size:14px;
}
input[type=text]{
  width:100%; font:22px Tahoma, Geneva; padding:0 5px; border:1px solid #aaa; border-radius:5px;
}
input[type=text]+div{
  height:28px; margin-bottom:5px;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
  <head>
    <meta http-equiv='content-type' content='text/html;charset=utf-8' />
    <meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
    <title>sweetScore &amp; SweetSort - by Jason Raymond Buckley</title>
    <link type='text/css' rel='stylesheet' href='external.css' />
    <script type='text/javascript' src='external.js'></script>
  </head>
<body>
  <div id='content'>
    <div class='page'>
      <div class='bar'><h1>sweetScore &amp; SweetSort</h1></div>
      <div class='main'>
        <label for='sweet_score_in'>sweetScore</label>
        <input id='sweet_score_in' type='text' value='' />
        <div id='sweet_score'>0</div>
        <label for='sweet_match_in'>SweetSort <em>['how', 'now', 'brownest', 'Brown', 'Cow']</em></label>
        <input id='sweet_sort_in' type='text' value='' />
        <div id='sweet_sort'></div>
      </div>
    </div>
  </div>
</body>
</html>