Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to perform a dynamic search within a nested array?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use the Array.prototype.some() to tests whether at least one element in the array passes the test:

function dynamicSearch() {
  return tracklist.filter(track =>
    track.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    track.artist.some(artist =>
      artist.toLowerCase().includes(searchTerm.toLowerCase())
    )
  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading