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

Tell us what’s happening:

I feel like I am missing something quite obvious but I can not figure it out for the life of me. Could someone point me in the right direction?

Step 63:

The sort() method converts elements of an array into strings and sorts them based on their UTF-16 code units values.

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

numbers.sort();
console.log(numbers); // Output: [1, 100, 2, 3, 4, 5]
You can see 100 comes right after 1, which is not supposed to happen. This is a default behavior of the sort() method you can fix by passing in a callback this way:

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

numbers.sort((a, b) => a - b);
console.log(numbers); // Output: [1, 2, 3, 4, 5, 100]
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.sort(() => Math.random - 0.5);

Your browser information:

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

Challenge Information:

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

Hi! Two things:

  • First, don’t modify the braces in the original function, it triggers an error.
  • Second, Math.Random() is a function, remember that functions take parentheses :wink:

Hopes it helps.

1 Like
const shuffle = userData?.songs.sort(() => {Math.random() - 0.5});

This is what I had originally tried but it was also not completing the section.
What am I missing?

Mantain the original braces:

const shuffle = () => {
// here put your original code but with the parentheses in the Math.random()
};

3 Likes

Holy moly! Thank you so much! :star_struck: I was desperately confused.