Can someone please explain how this code works?

I once again had to look at the solution code as my code wasn’t working and I just couldn’t figure out why! So I replaced the code but I don’t understand it! A link to the challenge is Challenge sortYears()

const sortYears = arr => arr.sort((x, y) => y - x);

const years = [1970, 1999, 1951, 1982, 1963, 2011, 2018, 1922]

// Should print [ 2018, 2011, 1999, 1982, 1970, 1963, 1951, 1922 ]

Hi there.

It may be helpful to you to read the documentation on how the .sort() function of the Array object works. The MDN documentation is a great resource for this.

In any case, let’s step through what’s happening.

We are defining a function, sortYears, using the arrow-notation. This function accepts a single input, the parameter arr.

The “body” of our function is therefore:

arr.sort((x, y) => y - x);

Referring back to the documentation for Array.prototype.sort(), we know that the .sort() method requires a callback function. The callback function for .sort() is what compares our values to work out how to sort them.

In our function, we are using an anonymous arrow-notation function as the comparator:

(x, y) => y - x

The output of the comparison function determines how the items are sorted. I’ll explain how this works in terms of the two values we are comparing, which are x and y.

  • If the return value of the comparison function is less than 0, then x comes before y in the sorted array.

  • If the return value of the comparison function is 0, then x and y are unchanged.

  • If the return value of the comparison function is greater than 0, then y comes before x in the sorted array.

Let’s examine this in terms of our first two items from the array, 1970 and 1999, and see how this works. We’ll say that x = 1970, and y = 1999.

Our function is (x, y) => y - x, and with our values for x and y this becomes (x, y) => 1999 - 1970.

1999 - 1970 = 29, and since 29 is greater than 0 we know that 1999 ought to come before 1970 in our sorted array.

This process is repeated for all the items in the array.

Hopefully that explanation helps, but let us know if you’re still confused. :slight_smile: