I don’t really understand the sort method. I tried looking only and at other posts but I still don’t get it. I understand map, reduce, and filter. The only understanding I have is that it sorts the items in an array by their unicode value if nothing is given. In the example I don’t get the arr.sort((a,b) => a - b) sort nums from least to greatest. I need help understanding what a and b represent and how sort iterates through the array.

**Your code so far**

function alphabeticalOrder(arr) {
// Only change code below this line
return arr
// Only change code above this line
}
alphabeticalOrder(["a", "d", "c", "a", "z", "g"]);

**Your browser information:**

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

Challenge: Functional Programming - Sort an Array Alphabetically using the sort Method

Ok so I added some console.logs to arr = [5, 6, 3, 2, 9] arr.sort((a,b) => a - b //c.log here//).
The output was 1, -3, -1, -9. So my understanding of the function above is that it iterates through the array with the first number being b and second being a. The second iteration would have a from the previous one be b and the next number be a. This is repeated until it has gone through all the numbers. In each iteration the fucntion performs an operation on them (a-b) and returns the value. After it has done this for all numbers it sorts them from least to greatest value. Is this correct?

The exact order that the array is traversed isn’t really important here. That depends upon which browser or engine is running your code.

What matters is that the sort function will compare two elements at a time, and your callback function determines how those two elements should be sorted relative to each other.

A positive return value means that b is ‘bigger’ and should come first. A negative return value means a is ‘bigger’ and should come first.

Your browser picks which elements to compare and how to move through the array to do the sorting. You just need to tell Javascript how to compare your array entries.

Bingo. Overall this is the benefit of built in stuff - you need to know what it does and how to use it, but exactly how the built in method accomplishes that task can change and it won’t impact your code.