I'm trying to return an album object given a specified track. Given this array:
const albumCollection = [
{
id: 2125,
title: 'Use Your Illusion',
artist: "Guns N' Roses",
tracks: ['November Rain', "Don't Cry"]
},
{
id: 2975,
title: '1999',
artist: 'Prince',
tracks: ['1999', 'Little Red Corvette']
},
{
id: 1257,
title: 'Transformer',
artist: 'Lou Reed',
tracks: ['Vicious', 'Perfect Day', 'Walking on the Wild Side']
},
And using the following function, both the commented and uncommented code returns undefined. I'm trying to understand why. What I'm trying to do is return the album as an object based on the track
name.
function getAlbumWithTrack(track) {
/*
const result = albumCollection.find((item) => item.id === track);
console.log(result);
*/
return albumCollection.find(function (title) {
return title.track === track;
});
}
console.log(getAlbumWithTrack('Little Red Corvette'));
console.log(getAlbumWithTrack('November Rain'));
console.log(getAlbumWithTrack('perfect day'));
CodePudding user response:
On this line:
return title.track === track;
There is no property called track
on your objects. It's called tracks
, and it's an array so it would never equal a string value. I suspect you're looking for this:
return title.tracks.includes(track);
For example:
const albumCollection = [
{
id: 2125,
title: 'Use Your Illusion',
artist: "Guns N' Roses",
tracks: ['November Rain', "Don't Cry"]
},
{
id: 2975,
title: '1999',
artist: 'Prince',
tracks: ['1999', 'Little Red Corvette']
},
{
id: 1257,
title: 'Transformer',
artist: 'Lou Reed',
tracks: ['Vicious', 'Perfect Day', 'Walking on the Wild Side']
}
];
function getAlbumWithTrack(track) {
return albumCollection.find(function (title) {
return title.tracks.includes(track);
});
}
console.log(getAlbumWithTrack('Little Red Corvette'));
console.log(getAlbumWithTrack('November Rain'));
console.log(getAlbumWithTrack('perfect day'));