Learn Basic String and Array Methods by Building a Music Player - Step 62

Tell us what’s happening:

Very stumped on this one. I’ve attempted a few different variations but with no success.

The example given:

const numbers = [4, 2, 5, 100, 1, 3];

numbers.sort((a, b) => a - b);
console.log(numbers); // Output: [1, 2, 3, 4, 5, 100]

The instructions given:

Use the sort() method on the userData?.songs array. For the callback, introduce Math.random() , and subtract 0.5 .

Your code so far

const shuffle = () => {
  userData?.songs((a,b) => Math.random(a) - b);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/ Safari/537.36

Challenge Information:

Learn Basic String and Array Methods by Building a Music Player - Step 62

OK, I don’t blame you for being confused here. I don’t think this step really explains how the sort function works and thus it is not very clear what you need to do inside of the callback and why you are subtracting 0.5. Also, the example uses two parameters passed into the callback but you don’t need them at all for this step, so that’s misleading as well.

What this step fails to mention is that the callback function for sort should return a number, and depending on whether that number is greater than 0, or less than 0 will determine whether the array is sorted in ascending or descending order. Since you want to sort this array randomly, you want the callback to return a number greater than 0 half the time and a number less than 0 half the time. Since Math.random() returns a random number between 0 and 1 then you can subtract 0.5 to create those odds. You don’t actually care what the values are being sorted since this is all random, so you don’t need to pass any parameters into the callback function. You just need to get a random number and subtract 0.5 from it.

I hope this is enough to help you figure out what you need to do.


Thanks for the help! I’ll keep working at it with your advice in mind.

don’t forget to call the sort function when doing this step and an issue I had here is that the program does not consider 0.5 and .5 to be the same.

If you didn’t just say this i would have been upset in the next few minutes. There is a vast difference in coding " call the sort function" and coding " use the sort function ON the userData?.songs array. It’s been frustrating playing a guessing game on what we should do, for me it’s so much so tthat I lose the information I want to learn and I’m just trying to find the solution so I can go back and match the lesson to the code to learn what it does.