Last active
September 6, 2021 05:01
-
-
Save anehkumar/b76491253505c03cd0e85a9d56baa7e7 to your computer and use it in GitHub Desktop.
Search Words in Array or Object Example Javascript React
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
let searchWord=(searchQuery, array, objectKey=null)=>{ | |
return array.filter(d =>{ | |
let data =objectKey? d[objectKey] : d //Incase If It's Array Of Objects. | |
let dataWords= typeof data=="string" && data?.split(" ")?.map(b=>b&&b.toLowerCase().trim()).filter(b=>b) | |
let searchWords = typeof searchQuery=="string"&&searchQuery?.split(" ").map(b=>b&&b.toLowerCase().trim()).filter(b=>b) | |
//let matchingWords = searchWords.filter(word=>dataWords.includes(word)) | |
let matchingWords = searchWords.filter((word)=> dataWords.find(a =>a.includes(word))) | |
return matchingWords.length | |
}) | |
} | |
let arrayOfObject = [ | |
{ | |
"address": "india city Punjab" | |
}, | |
{ | |
"address": "india country mohali" | |
}, | |
{ | |
"address": "mohali" | |
} | |
] | |
searchWord("punjaB", arrayOfObject, "address") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment