Skip to content

Instantly share code, notes, and snippets.

@Maybach91
Last active November 17, 2022 18:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Maybach91/fa565658d14423dc04f5d0954f87786f to your computer and use it in GitHub Desktop.
Save Maybach91/fa565658d14423dc04f5d0954f87786f to your computer and use it in GitHub Desktop.
Simple Fuzzy Search Vanilla Javascript #fuzzysearch #javascript
// Source: https://slimvoice.co/static/js/client_select.js
// Referenced by Owner at https://dev.to/winduptoy/a-javascript-free-frontend-2d3e
const clientSelects = document.querySelectorAll('.clientsSelect__client');
const emptyMessage = document.getElementById('clientsSelect__noneFound');
const clientNames = [];
clientSelects.forEach(function(el) { clientNames.push(el.dataset.clientName); });
function fuzzySearch(query, dataset) {
const q = query ? query.trim().toLowerCase() : '';
const matchingIndices = [];
if(q.length == 0) {
for(let i = 0; i < dataset.length; i++) {
matchingIndices.push(i);
}
return matchingIndices;
}
dataset.forEach(function(d, index) {
const s = d.trim().toLowerCase();
let i = 0;
let n = -1;
let l;
for (; l = q[i++] ;) if (!~(n = s.indexOf(l, n + 1))) return;
matchingIndices.push(index);
});
return matchingIndices;
}
function handleClientFilterInput(event) {
const results = fuzzySearch(event.target.value, clientNames);
for(let i = 0; i < clientSelects.length; i++) {
clientSelects[i].style.display = 'none';
clientSelects[i].classList.remove('clientsSelect__client--first');
}
for(let i = 0; i < results.length; i++) {
if(i == 0) clientSelects[results[i]].classList.add('clientsSelect__client--first');
clientSelects[results[i]].style.display = 'flex';
}
if(results.length == 0) {
emptyMessage.classList.remove('display--none');
} else {
emptyMessage.classList.add('display--none');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment