Exercise 9 / "sortYears()" / Mod. 5, JS Practice


#1

https://www.codecademy.com/paths/web-development/tracks/web-dev-js-arrays-loops-objects/modules/web-dev-intermediate-javascript-practice/lessons/intermediate-javascript-coding-challenge/exercises/sort-years

Hello!
I tried some alternative ways to solve the problem, I would like to know why they do not work:

Instruction)- Write a function sortYears() that takes in an array of years, and, using the built-in .sort() method, returns that array with the years sorted in descending order
const years = [1970, 1999, 1951, 1982, 1963, 2011, 2018, 1922]

Attempt 1:
const sorted = order => order.sort();
const sortYears = sorted => sorted.reverse();
console.log(sortYears(years));

PRINTS: [ 1922, 2018, 2011, 1963, 1982, 1951, 1999, 1970 ]

Attempt 2:
const sortYears = arr => {
arr.sort((newArr) => {
(newArr).reverse();
})
};
console.log(sortYears(years));
PRINTS: ERROR

GIVEN SOLUTION
const sortYears = arr => arr.sort((x, y) => y - x);
console.log(sortYears(years))


#2

As we can see in the given solution, Array.sort() takes a callback that ensures we have valid ordering. When the callback is omitted, JS sorts by the first digit, then the second, then the third, etc.

 > array = [1,1,2,3,5,8,13,21,34,55]
<- > (10) [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
 > array.sort()
<- > (10) [1, 1, 13, 2, 21, 3, 34, 5, 55, 8]
 >

The callback in the solution,

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

sorts according to where the difference appears in the number line. When y - x is negative, x and y are swapped. One might imagine a merge sort going on in the background.


#3

I tried to get same result by using the “reverse()” method in a function, and do not know why it did not work, as it did not reverse the order of the original array.


#4
 > array.sort().reverse()
<- > (10) [8, 55, 5, 34, 3, 21, 2, 13, 1, 1]

As we can see, the reverse method works as expected. Note how that without the callback, the order is based upon first digits.

On inspecting the years list,

 > years = [1970, 1999, 1951, 1982, 1963, 2011, 2018, 1922]
<- > (8) [1970, 1999, 1951, 1982, 1963, 2011, 2018, 1922]
 > years.sort()
<- > (8) [1922, 1951, 1963, 1970, 1982, 1999, 2011, 2018]
 > years.sort().reverse()
<- > (8) [2018, 2011, 1999, 1982, 1970, 1963, 1951, 1922]

we see that it can be sorted without the use of a callback to bring the correct order.

Suggest reset the lesson and try again using the no callback approach, first. Let us know what error message you are given.