Home > database >  How do I shuffle items in an array, using value as audio source in React?
How do I shuffle items in an array, using value as audio source in React?

Time:11-29

I fetched an array of songs from an API ,mapped over it and used the string in the array as audio source. Currently I'm trying to add a shuffle functionality to my audio player web app but I don't know where to begin.

CodePudding user response:

You can use Math.random() function which returns a floating-point number between 0 and less than 1 then multiply it by the length of your array and pass that number to Math.floor() function and use that final number result as the index of your array of songs.

const songs = ['1st song','2nd song','3rd song', '4th song']

const getRandomSong = max => {
  return songs[Math.floor(Math.random() * max)];
}

const randomSong = document.querySelector('.randomSong');
const btnRandomizer = document.querySelector('.btnRandomizer');
btnRandomizer.addEventListener('click', () => randomSong.textContent = getRandomSong(songs.length))
<button class='btnRandomizer'>Randomize</button>
<p>Random song: <span class='randomSong'></span></p>

NOTE: this example above can seem like its "stuck" at some point, but that's just the way it works for example it can result number 2 twice or 10 or more times in a row.

That's why below I've created another example where I'm storing that randomized value(randomNum) to a global variable (in the outer scope)(prevNum).

const songs = ['1st song', '2nd song', '3rd song', '4th song']

let prevNum;
const getRandomSong = max => {
  const randomNum = Math.floor(Math.random() * max)
  if (prevNum === randomNum) {
    let newRandomNum = randomNum === 0 ? randomNum   1 : randomNum - 1
    prevNum = newRandomNum;
    return songs[newRandomNum];
  } else {
    prevNum = randomNum;
    return songs[randomNum];
  }
}

const randomSong = document.querySelector('.randomSong');
const btnRandomizer = document.querySelector('.btnRandomizer');
btnRandomizer.addEventListener('click', () => randomSong.textContent = getRandomSong(songs.length))
<button class='btnRandomizer'>Randomize</button>
<p>Random song: <span class='randomSong'></span></p>

Further explanation if you are interested is the part of initializing newRandomNum using the ternary operator as to avoid possible issue if you were to simply use 1 or -1 you may encounter a case scenario where you are trying to access an element above the index of the last element in your array or an index below 0 which in both cases would resolve to undefined.

  • Related