I'm developing a personalized search feature. Currently, when I type "The R," the search results list starts with The Fellowship of the Ring because the phrase "the ring" is in its .text property. However, I want The Return of the King to appear first. Is there a way to prioritize the .name field or arrange the match array based on the name .field and input text?
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>
JAVASCRIPT
const searchIndex = async searchText => {
const res = await fetch('/data/index.json');
const index = await res.json();
matchList.classList.remove("d-none");
// Retrieve matches for the current text input
let matches = index.filter(index => {
const regex = new RegExp(`${searchText}`, 'gi');
return index.name.match(regex) || index.text.match(regex);
});
// Clear the search when input or matches are empty
if (searchText.length === 0) {
clearSearch();
}
outputHtml(matches);
};
function clearSearch(){
matches = [];
matchList.classList.add("d-none");
}
// Display 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;
}
};
index.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"
}
]