0

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'));

1 Answer 1

5

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'));

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much, it always seems that it's the little things like a misspelling. I appreciate it!
@ConorDerhammercderhammer Almost half an hour has passed: remember to mark the answer as accepted since the poster’s solution worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.