FAQ: Code Challenges: Intermediate JavaScript - sortYears()

This community-built FAQ covers the “sortYears()” exercise from the lesson “Code Challenges: Intermediate JavaScript”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Web Development

FAQs on the exercise sortYears()

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

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

I don’t understand what " (x, y) => y - x " is doing, why would it return a year and not the value of y minus x?

1 Like

I want to know that too, I don’t understand that… Can some one explain how does it work?

because of how sort works, here is useful documentation:

we pass our own function to the sort method to determine sorting order. The result of y - x is then used to determine were the element should be sorted. for example, the first two elements in our array are:

1970, 1999

so if we then fill in our function which determine sorting order:

(1970, 1999) => 1999 - 1970

which gives a a value higher then 0, which means y comes before x.

in short, the .sort() method will call your function to determine sorting order.