.sort() Return Largest Numbers in Arrays

Tell us what’s happening:
I thought I understood this => (const dontGetIt = (a, b) => b - a;), I was wrong I don’t get it at all. I can’t figure out why if const => (dontGetIt = (a, b) => a - b;) it does not work. Someone can explain me please.

   **Your code so far**

function largestOfFour(arr) {
let newArr = [];
const dontGetIt = (a, b) => b - a;
for (let i = 0; i < arr.length; i++) {
 return newArr;

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
   **Your browser information:**

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

Challenge: Return Largest Numbers in Arrays

Link to the challenge:

The MDN JavaScript documentation on sort is pretty good. Basically, the sign of the result from the sorting function determines how the array will be sorted. If the result is positive, b will be treated as smaller. If the result is negative, a will be treated as smaller.

1 Like

.sort() doesn’t sort numbers by default, so you have to provide it with a callback to sort the number with.
When sorting, the method gives the callback two elements (a and b) and see what comes out, if the answer is negative, a is closer to the beginning of the array. If the answer is positive, b is closer to the beginning of the array.

Now applied to an array of numbers, if you give .sort() the callback: (a,b)=>b-a, it returns a negative number to .sort() when a > b, putting a closer to beginning of array, then end result is the array is sorted in descending order. Biggest number first.

If you give .sort() the callback (a,b)=>a-b it does the opposite and returns a negative number when a<b. Therefore this would sort the array in ascending order, smallest number first.

1 Like

@MatchaCrisp thank you very much. Now I get it thanks to you.

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