Last active
August 12, 2024 22:55
-
-
Save marcelo-ribeiro/e7ad24377f0fcb884048ab68c452f120 to your computer and use it in GitHub Desktop.
javascript searching texts in a array of properties in a list of objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const list = [ | |
{ name: "Marcelo Ribeiro", short_name: "tchelo" }, | |
{ name: "Leonardo Costa", short_name: "leo" }, | |
{ name: "Victor Tanure", short_name: "vitrola" }, | |
{ name: "Matheus Oliveira", short_name: "rary" } | |
]; | |
let filteredList = [...list]; | |
const searchProps = ["name", "short_name"]; | |
let timeout = null; | |
const removeAccents = (text) => { return text; }; | |
const searchText = (searchedText, text) => { | |
const searchedTextSplitted = searchedText.split(" "); | |
const textSplitted = text.split(" "); | |
const hasIncludedWords = searchedTextSplitted.every((searchTextWord) => { | |
return textSplitted.some((propTextWord) => { | |
return propTextWord.includes(searchTextWord) | |
)}; | |
}); | |
return hasIncludedWords; | |
}; | |
const handleFilterList = (searchedText) => { | |
filteredList = list.filter((listItem) => { | |
const hasItemList = searchProps.some(searchProp => { | |
const propText = removeAccents(listItem[searchProp]); | |
searchText(searchedText, propText) | |
}); | |
return hasItemList; | |
}); | |
}; | |
const handleSearchText = (searchedText) => { | |
!!timeout && clearTimeout(timeout); | |
if (!searchedText || searchedText.length < 2) { | |
filteredList = [...list]; | |
return; | |
}; | |
searchedTextFormatted = removeAccents(searchedText); | |
timeout = setTimeout(() => handleFilterList(searchedTextFormatted), 1500); | |
}; | |
// Example of use | |
handleSearchText("mar rib"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment