Build a library project


#1

OK so I am on task 25 of the build a library project and on trying to accomplish what it is telling me to do which is " Create a method called shuffle for the CD class. The method returns a randomly sorted array of all the songs in the songs property." To achieve this I seen using the fisher yates shuffle is the best I understand what it does and how it works I just don’t under stand one small part of it

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

function shuffle(array) {
for (let i = array.length - 1; i > 0; i–) {
let j = Math.floor(Math.random() * (i + 1));
let temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}

const result = shuffle(array);
// these three lines right here what do they do ?
let temp = array[i];
array[i] = array[j];
array[j] = temp;

if someone could go step by step with what each of the lines do that would be great I know they swap the values around I just dont see the need for “array[i] = array[j];” to be there when there is already “array[j] = temp;”.


#2

That is a classic swap. Element [i] is swapped with element [j]. The temp variable is a temporary holding register for the value [i] so that element can be overwritten with value [j]. Then element [j] is overwritten with the temp value.


#3

Got another question for some reason my shuffle isn’t working properly what could be the cause ?

class CD extends Media {
constructor(title,runTime,producer) {
super(title)
this._runTime = runTime;
this._songTitles = [];
}
get runTime () {
return this._runTime
}
get songTitles () {
return this._songTitles
}
addSongTitles (songTitles) {
this._songTitles.push(songTitles);
}
shuffle (songsArr) {
let i = songsArr.length;

while(--i > 0) {
  let randomIndex = Math.floor(Math.random() * (i+1));
  
  
 	 let temp = songsArr[randomIndex];
    songsArr[randomIndex] = songsArr[i]; 
    songsArr[i] = temp;

}

}
}

const majorLaser = new CD (‘lightshow’, 26, ‘Joey’);

majorLaser.addSongTitles([‘raining’,‘black butterfly’, ‘all in your name’, ‘be sure’]);

majorLaser.shuffle(majorLaser.songTitles);

console.log(majorLaser.songTitles);