Build library - shuffle method

Hey guys, I feel so proud of myself to have produce this, google and the forum helped me a lot but I could not find a correct solution to this “Shuffled method”

I was not satisfy by the fact that 100% of the code I found were returning an array.length = this.songs.length with songs that can be found multiple times in the returned array.

So I produce this method that does not allow a song to repeat in the returned array…

J J Cale Loves you!!

shuffle() { let shuffledArray=[]; while(shuffledArray.length<this.songs.length) { let randomNumber = [Math.floor(Math.random()*this.songs.length)]; if(!shuffledArray.includes(this.songs[randomNumber])){shuffledArray.push(this.songs[randomNumber]);} } return shuffledArray; }

Nice!, very clean solution, I solved it differently (took me a while):

    const usedIndexes = [];
    const suffledArr = [];
    //1) Iterate over the array of elements (songs)
    for(let i=0; i<this.songs.length; i++){
      //2) In each iteration generate a randomindex
      let randomIndex = Math.floor(Math.random() * this.songs.length);
      //3) Store the randomIndex in an array (usedIndexes), making sure you haven't added it yet, if you have, try again
        //4) Get the element of the original array that is in the randomIndex position and push it to a new array (shuffledArr)
      } else {
        //5) If the array already has the element, decrease iterator to retry
    return suffledArr;
1 Like