-1

Hello everyone I'm doing this music player and this is the song loader but the problem is that when I try to assing the value to song constant with lookSongbyId function it returns me an error idk why

let queue = [
    {
        id: 1,
        name: 'Crush',
        artist: 'Glades',
    }
]

const loadSong = (id) =>{


    function lookSongbyId(id)
    {
        queue.forEach(currentSong => {
            if(currentSong.id == id )
            {
                return currentSong
            }   
        })
    }

    const song = lookSongbyId(id)


    console.log(`la canción ${song.name} ha sido cargada`)
}
loadSong(1)

song constant is undefined, and I dont know why aghhh If u could help me with this code I've been so thankful with u :DDD

sankiago
  • 79
  • 9
  • Syntax: `functionlookSongbyId(id)`. Also, you should load the whole array of `queue` and then run each object of array through `.forEach()`. – zer00ne May 29 '21 at 17:14
  • thanks i didnt realize of this typo but it was only when i wrote the question, in my original code it isnt but it doesnt work :c – sankiago May 29 '21 at 17:17
  • Returning from a forEach handler goes to the next iteration, it does not return a value for its outer function. Use a for of loop instead, or one of the suggested answers – Ruan Mendes May 29 '21 at 17:21

4 Answers4

3

you can use directly filter if you want to return more than item or find if you want only want (if the id is unique)

const queue = [
      {
        id: 1,
        name: 'Crush',
        artist: 'Glades',
      },
      {
        id: 2,
        name: 'Another Song2',
        artist: 'Favio Figueroa',
      }
    ];
    const useFilter = queue.filter((row) => row.id === 1 );
    console.log('useFilter', useFilter) // [ { id: 1, name: 'Crush', artist: 'Glades' } ]
    const useFind = queue.find((row) => row.id === 2 );
    console.log('useFind', useFind) // { id: 2, name: 'Another Song2', artist: 'Favio Figueroa' }

you can add in your function that logic.

Favio Figueroa
  • 264
  • 1
  • 8
0

You can simplify your function to just use find which will return the matched song.

let queue = [
    {
        id: 1,
        name: 'Crush',
        artist: 'Glades',
    }
]

const loadSong = (id) =>{
    const song = queue.find(x => x.id === id)
    console.log(`la canción ${song.name} ha sido cargada`)
    return song
}
loadSong(1)
jmargolisvt
  • 5,722
  • 4
  • 29
  • 46
-1

Assuming the functionlookSongbyId is just misspelled (you must write function lookSongbyId), the forEach function cannot be used to return a value, as indirectly said here. Use a for ... of or .find() to retrieve the element

Andrea Roveroni
  • 184
  • 1
  • 6
-1

Don't create a function for the song search, you can use find and get the right song seamlessly:

const loadSong = (id) => {
    const song = queue.find( sng => sng.id === id);
    console.log(`la canción ${song.name} ha sido cargada`)
}
Dani
  • 745
  • 7
  • 12