Shuffling an array, solved. Shuffle the songs! (Solution for an extra challange from the "Build a Library" project.)


#1

Hello, I have been working on this, and 2 related topics in this forum seemed like they are not giving the solution. So, I just wanted to share my code for my coder friends who are looking for a solution to shuffle their array.

So, the project is this : Build A Library

Challenge is this : Create a method called shuffle for the CD class. The method returns a randomly sorted array of all the songs in the songs property.

My solution is this:

  shuffle () {
const index = []; 
const songList = this._songs; 
const shuffledSongs = []; 

for (let i= Math.floor(Math.random()* songList.length); index.length<songList.length;
     i=Math.floor(Math.random()*songList.length)) {
  if (!index.includes(i)){
  index.push(i);
  } else {i=Math.floor(Math.random()*songList.length)}
}

const shuffler = (arr,shuf) => {
for (let j = 0; j<songList.length; j++)
  shuffledSongs[j]=arr[shuf[j]]
}

shuffler(songList,index);
return shuffledSongs;
  }

Note: Sorry for any problems in my code, in advance. And I appreciate any improvements.