javascript - 如何在javascript中按相关性对搜索结果进行排序

标签 javascript arrays json sorting search

我正在构建一个自定义搜索,到目前为止,如果我输入“The R”,我会首先得到 The Fellowship of the Ring 的结果列表,因为短语“the ring”在它的 .text 中。我希望王者归来是第一个。有没有一种方法可以使 .name 字段具有更多相关性,或者根据名称 .field 和输入文本对匹配数组进行排序?

HTML

<section class="container-fluid px-0 justify-content-center">
  <div class="row no-gutters">
    <div class="col d-flex justify-content-center search">
      <form class="form-inline position-relative">
        <input id="search" class="form-control form-control-search" type="text" placeholder="Search..." aria-label="Search">
      </form>
      <div id="match-list" class="d-none"></div>
    </div>
  </div>
</section>

java 脚本
const searchIndex = async searchText => {
 const res = await fetch('/data/index.json');
 const index = await res.json();

  matchList.classList.remove("d-none");
 // Get matches to current text input
 let matches = index.filter(index => {
  const regex = new RegExp(`${searchText}`, 'gi');
  return index.name.match(regex) || index.text.match(regex);
 });

 // Clear when input or matches are empty
 if (searchText.length === 0) {
   clearSearch();
 }

 outputHtml(matches);
};

function clearSearch(){
  matches = [];
  matchList.classList.add("d-none");
}

// Show results in HTML
const outputHtml = matches => {
 if (matches.length > 0) {
  const html = matches.map(function(match){
      return `<a href="${match.url}">
      <div class="media mb-2">
        <div class="component-icon-slot my-auto" style="background-image: url('/img/${match.url}/icon.png"></div>
          <div class="media-body pl-2">
            <h3 class="mt-0 mb-0">${match.name}</h3>
            <b>${match.type}</b><br/>
            <i>Found in <b>${match.product}</b></i><br/>
            ${match.text}
          </div>
        </div></a>`
    }
}).join('');
  matchList.innerHTML = html;
 }
};

索引.JSON
 [
  {
    "name": "The Fellowship of the Rings",
    "type": "book",
    "text": "Bilbo reveals that he intends to leave the Shire for one last adventure, and he leaves his inheritance, including the Ring, to his nephew Frodo. Gandalf investigates...",
    "url": "books/the-fellowship-of-the-rings",
    "product": "Books"
  },
  {
    "name": "The Two Towers",
    "type": "book",
    "text": "Awakening from a dream of Gandalf fighting the Balrog in Moria, Frodo Baggins and Samwise Gamgee find themselves lost in the Emyn Muil near Mordor and discover they are being tracked by Gollum, a former bearer of the One Ring.",
    "url": "books/the-two-towers",
    "product": "Books"
  },
  {
    "name": "The Return of the King",
    "type": "book",
    "text": "Gandalf flies in with eagles to rescue the Hobbits, who awaken in Minas Tirith and are reunited with the surviving Fellowship.",
    "url": "books/the-return-of-the-king",
    "product": "Books"
  }
]

最佳答案

您可以映射您的数据以包括相关点:

const index = await res.json();
const searchTextLowercased = searchText.toLowerCase();

const rankedIndex = index.map(entry => {
    let points = 0;

    if (entry.name.toLowerCase().includes(searchTextLowercased)) {
        points += 2;
    }

    if (entry.text.toLowerCase().includes(searchTextLowercased)) {
        points += 1;
    }

    return {...entry, points};
}).sort((a, b) => b.points - a.points);

这样,您就对 rankedIndex 中的结果进行了排名。常量

请记住,您的代码可能需要进行一些重构,因为您在每次搜索时都在获取数据。我假设你的 searchIndex()每次按键或类似的东西都会被调用。

关于javascript - 如何在javascript中按相关性对搜索结果进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61857573/

相关文章:

使用户在多维数组中输入行和列的c++代码

Javascript - 当数组包含一个对象和一个数组时检查两个数组是否相等

json - 如何将字符串作为 json 转换为简单字符串 - SwiftyJSON

json - Swift 3、Alamofire 4、JSON 字典 : Only displaying last JSON entry

json - 转置 JSON 字典列表以在 R 中进行分析

javascript - webkit css3 列文本选择

javascript - 不以科学计数法显示的 JavaScript 数字可以有多小?

javascript - 从日期时间戳中删除末尾的 'UTC' 文本

javascript - 工厂中的 AngularJS $scope

javascript - 如何将 for in 循环结果的值打印到数组中