I am trying to filter through an Array of Objects (Albums in my case), but I am getting this Error and everything I tried did not work.
My Searchbar :
<input type="search" placeholder={" "} onChange={e => onChangeHandler(e.target.value)} value={text}/>
My onChangeHandler
const onChangeHandler =(text) => {
let matches = []
if (text.length > 0){
matches = albums.filter(album => {
const regex = new RegExp(`${text}`, "gi")
return (album.artist.matches(regex));
});
}
console.log('matches', matches)
setSuggestions(matches)
setText(text)
}
When I try, it works and I get the matches in the console, but only if I type everything correctly and case sensitive. That is not the goal tho.
return (album.artist === text);
CodePudding user response:
You can use includes method of strings for this. So for your example something like this:
matches = albums.filter(album => album.artist.toLowerCase().includes(text.toLowerCase()));
If you want the search to be case sensitive, you should remove toLowerCase methods.
CodePudding user response:
There are probably 2 issues in your code. First it doesn't seem to find the album.artist
so make sure your object looks correct.
Secondly matches()
is not a function on a String and you probably meant match()
let albums = [{
artist: "Me"
}, {
artist: "You"
}]
const onChangeHandler = (text) => {
let matches = []
if (text.length > 0) {
matches = albums.filter(album => {
const regex = new RegExp(`${text}`, "gi")
return (album.artist.match(regex)); // Here matches => match
});
}
console.log('matches', matches)
//setSuggestions(matches)
//setText(text)
}
onChangeHandler("mE")
onChangeHandler("me")
onChangeHandler("yo")