Let’s say that I have a music app that showcases the tracks within a selected playlist. If I’m using React, I would have a state for the tracklist
which would contain an array of objects. The object would contain information about the track. Here’s an example:
{
id: 1
name: 'Calm Down'
artist: ['Selena Gomez', 'Rema']
album: 'Calm Down'
}
I have another state for the search text called searchTerm
. If I’m trying to search for a specific song name, I can write some code like this:
function dynamicSearch() {
return tracklist.filter(track =>
track.name.toLowerCase().includes(searchTerm.toLowerCase()))
}
But how do I search for an artist, in this example Selena Gomez, if there’s more than one and they’re inside an array?
3
Answers
You can do it the same way. JS Arrays have "includes" method too.
You can read more here – Array.prototype.includes()
If you need to search track by substring of artist’s name the function can be like this:
You can use the Array.prototype.some() to tests whether at least one element in the array passes the test: