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

Hello Everyone!

I don’t have a shuffle function yet.

My code that I wrote:
userData?.songs.sort(() => Math.random() - 0.5);

Then the message comes
You should not modify the existing shuffle function.

userData?.songs.sort(() => Math.random() - 0.5);

what’s wrong? I don’t see any error.

Can you help me please?

Best Regards
Michael
Text of the task:
In earlier steps, you learned how to work with the sort() method to sort the songs in alphabetical order. Another use case for the callback function is to randomize an array.

One way to randomize an array of items would be to subtract 0.5 from Math.random() which produces random values that are either positive or negative. This makes the comparison result a mix of positive and negative values, leading to a random ordering of elements.

const names = ["Tom", "Jessica", "Quincy", "Naomi"];
names.sort(() => Math.random() - 0.5);
Use the sort() method on the userData?.songs array. Pass a callback to the method, and return the result of Math.random() - 0.5.



### Your browser information:

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

### Challenge Information:
Learn Basic String and Array Methods by Building a Music Player - Step 71
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures-v8/learn-basic-string-and-array-methods-by-building-a-music-player/step-71

ok, it’s not logical for me… But I copied the existing Sort function and changed it to shuffle variable.

How do you decide that you need the function that way?

But now I’ve moved on…

const shuffle = () => {

userData?.songs.sort(() => Math.random() - 0.5);}

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.