The javascript I have returns a random item from an array and I’m trying to figure out the best way to remove that item from the array after it’s been console logged. I keep feeling that things like splice, pop, shift, etc. aren’t what I’m looking for but I could be wrong but my brain is fried at the moment. Code is below.
// program to get a random song from an array
function getRandomSong(arr) {
// get random song value
const randomSong = Math.floor(Math.random() * arr.length);
// get random song
const song = arr[randomSong];
return song;
}
const songList = ["i'm better off without you", "the other side of you",
"unbreakable", "the champion", "he was our champion",
"dream of you", "parallels", "I'm lost I can't find my way back",
"you can't handle the truth", "he hopes he wants you",
"wish of my affection", "remember his eyes", "stop dreams",
"confusion", "turn away", "hide the hurt", "save the night",
"get out", "gone away", "killing the mood", "beautiful darkness"];
const result = getRandomSong(songList);
console.log(result);
Also is there a better way to view the result other than the console log? I tried return but it wasn’t working.
It did! The array that was shown didn’t include the randomly selected item. Eventually I’ll want it to update the original array but right now happy that this does work.
I had to do it further up in the code because putting it at the end it kept telling me arr is not defined in the console.
// program to get a random song from an array
function getRandomSong(arr) {
// get random song value
const randomSong = Math.floor(Math.random() * arr.length);
// get random song
const song = arr[randomSong];
arr.splice(randomSong,1)
console.log(arr);
return song;
}
const songList = ["i'm better off without you", "the other side of you",
"unbreakable", "the champion", "he was our champion",
"dream of you", "parallels", "I'm lost I can't find my way back",
"you can't handle the truth", "he hopes he wants you",
"wish of my affection", "remember his eyes", "stop dreams",
"confusion", "turn away", "hide the hurt", "save the night",
"get out", "gone away", "killing the mood", "beautiful darkness"];
const result = getRandomSong(songList);
console.log(result);
the output when I test this code shows the arr has changed:
// [object Array] (20)
["i'm better off without you","the other side of you","the champion","he was our champion","dream of you","parallels","I'm lost I can't find my way back","you can't handle the truth","he hopes he wants you","wish of my affection","remember his eyes","stop dreams","confusion","turn away","hide the hurt","save the night","get out","gone away","killing the mood","beautiful darkness"]
"unbreakable"
(you can see the song selected to be removed was unbreakable and it is gone from the arr)
btw. to log the arr after the getRandomSong you just need to call
console.log(songList)