FAQ: Code Challenges: Intermediate JavaScript - sortYears()

This returns what I need -
const sortYears = (arr) =>
arr.sort((e1, e2) => e2 > e1);
so far so good.
But when I try the same code with curly braces to demarcate the code blocks, it returns me undefined.
const sortYears = (arr) => {
arr.sort((e1, e2) => {e2 > e1})};

Can somebody please explain why?

What’s wrong having the curly braces? I thought it is good practice while creating any arrow function.
Please help!!

If we consult the documentation:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

which includes syntax we see:

(param1, param2, …, paramN) => { statements } 
(param1, param2, …, paramN) => expression
// equivalent to: => { return expression; }

we see the shorthand (line 2, omitting both curly brackets and return).

so if you want the curly brackets, you no longer have an implicit return, so you will also have to include the return keyword

the shorthand only works functions which have a body of a single line.

Thank you.
Makes sense.

Regards
Gopal

Honestly I didn’t think it was so (simple). I had to rely on documentation and ended up finding a good approach to it but I didn’t expect a solution to this exercise could be written in just one line.

Anyways, here is my code nonetheless

function sortYears(input) {
  input.sort((year1, year2) => {
  if (year1 < year2) return 1;
  if (year1 > year2) return -1;
  else return 0;
  });
  return input;
}

const years = [1970, 1999, 1951, 1982, 1963, 2011, 2018, 1922];
console.log(sortYears(years));

Prints exactly what we want

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

my focus on these exercises is to complete them in a very simple way.
This also works

// Write your code here:
const years = [1970, 1999, 1951, 1982, 1963, 2011, 2018, 1922]; 
const sortYears = arr => {
  arr.sort();
  return arr.reverse();
};






// Feel free to uncomment the below code to test your function:

console.log(sortYears(years))
// Should print [ 2018, 2011, 1999, 1982, 1970, 1963, 1951, 1922 ]

in documentation it offers a compareFunction, this works:

const sortYears = (arr) => {
  return arr.sort((a, b) => {return b - a});
}

The hint for this exercise says to pass in your own function (in this case it gives one called checkYears). However, I found the below code will pass the tests without using checkYears:

const sortYears = years => years.sort((a, b) => b - a);

What am I missing?

Thank you!

You are free to decide if you want to use checkYears as callback or an anonymous callback function.

declaring the function function means you can re-use it, which is not possible with an anonymous function

1 Like

I see a lot of solutions here - super interesting to see how other people solved this.
This is my solution:

const sortYears = (arr) => {
  return arr.reverse(arr.sort());
}

Short and efficient :slight_smile:

3 Likes

This was my solution too. I knew there was a reverse method and wasn’t sure if you could call two methods at once on an array, but first pass and it worked like a charm.

PHEW. :sweat_smile:

// another solution

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

// first sort them in ascending
const sortYearsAscending = arr =>{
return arr.sort()}

// then sort them in descending
const sortYearsDescending=(arr)=>{
let sortedDescending=;
for (let i=arr.length-1;i>=0;i–){
sortedDescending.push(arr[i])
}
return sortedDescending;
}

let sortedYears=sortYearsAscending(years)
console.log(sortedYears)

console.log(sortYearsDescending(sortedYears))

This was clearly the easiest way to do it, but I didn’t know about the .reverse() object.

The way I wanted to do it was let it sort normally, in descending order, and then take that and flip the array with a for loop that iterates backwards. This would print the array in descending order and then list my new array in ascending order. So it kind of did what I wanted it to, but it wouldn’t pass because it wanted to show the results of .sort() first.

Why wouldn’t it work this way?

I am sorry, but I am totally lost on this one.

I simply do not understand why 1999 - 1970 does return a sort order. For me it returns 29…

The MDN documentation is also kind of cryptic to me. It takes about optional arguments as well as FirstEl and SecondEl and I have no clue what that refers to.

Also - looking at the solution - I cannot understand how this can be a solution at all? The function that is suggested is commented out, so how can that work???

29 is indeed returned, but as you can see in the documentation:

  • If compareFunction(a, b) returns a value > than 0, sort b before a .
  • If compareFunction(a, b) returns a value ≤ 0, leave a and b in the same order.

29 is greater then zero, so b (1970) sort before a (1999)

you are not implementing your own sorting algorithm here, that has already been done. You use this built-in method where you can specify the sorting condition

2 Likes

ah, ok, I think now I get it.

Positive numbers (e. g. a 29) would sort b before a, anything below (like e. g. -29) sort a before b

Given the underlying sorting, I think a is already sorted before b. So like the docs say:

I don’t anything happens given the values are already in the right order

But other then that, you seem to understand to now :slight_smile:

1 Like

const sortYears = (arr) => (arr.sort()) works fine so why should i add the x - y in it?

I just wanted to give some feedback on the instructions.

“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”

My issue with this is it does not indicate the the function should be passed to the sort method, simply to make a function using the sort method. While the provided documentation does cover this aspect, if you were to go about attempting to do this without looking at cheatsheets or documentation to challenge yourself, it would be confusing when you see the correct result being returned and then suddenly the error message says to pass the function to the sort method. Very frustrating for someone new to JavaScript. I made a function, sorted the array and then made a for loop that produced a reversed array; so it felt like I had followed the instructions to the best of my ability. It would have been easier for me to focus my efforts had I know what was expected in a clearer manner.

I used the sort method, then searched up the reverse method which worked, not sure if this is how I was meant to solve this task but it worked!

Why would this code not be accepted?

const sortYears = years => {
  let ascendingYears = years.sort();
  let descendingYears = [];
  for (let i = ascendingYears.length-1; i >= 0; i--) {
    descendingYears.push(years[i]);
  };
  return descendingYears;
}

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

console.log(sortYears(years))
// Should print [ 2018, 2011, 1999, 1982, 1970, 1963, 1951, 1922 ]