I would like to understand how to use the .filter method to search through an array within an array. I am creating a collection array that is filled with album objects. Within the album objects are a property named tracks which itself is an array filled with track objects.
function addToCollection(title, artist, yearPublished, tracks) {
const album = {
title: title,
artist: artist,
yearPublished: yearPublished,
tracks: tracks,
}
collection.push(album);
return album;
} // end addToCollection
function addTrack(trackNumber, name, duration) {
const track = {
trackNumber: trackNumber,
name: name,
duration: duration
}
return track;
}
I am writing a search function to return certain albums if they meet the search criteria. The following line of code will return an array that contains the album objects that match the .artist property from the parameter that was passed in.
function search(query) {
const foundArtist = collection.filter( x => x.artist === query.artist );
My question is how to do use the .filter method to sort through the array of tracks within each album to find an individual track name or track duration.
This following code does not find the track name even though query.trackName exists.
const foundTrackName = collection.filter( x => x.tracks.name === query.trackName);
Whereas when I specify the specific track it does return the entire album.
const foundTrackName = collection.filter( x => x.tracks[4].name === query.trackName);