Inequality condition not working: Sort an Array Alphabetically using the sort Method

Tell us what’s happening:

Hello,

I think my solution is right, since I am just reversing the logic of the reverseAlpha method given in the example for this challenge, but the array remains the same after calling the function instead of being sorted. I copy and pasted the solution given in the hints, which also tests (a > b) as in mine, but the array is not being sorted either.

When trying a solution that implements (a - b) instead of (a > b) however, program passes. Is this a bug in the challenge?

Thanks!

Your code so far


function alphabeticalOrder(arr) {
  // Add your code below this line
  
  newArr =  arr.sort((a, b) => (a > b));
  
  // Add your code above this line
}
console.log(alphabeticalOrder(["a", "d", "c", "a", "z", "g"]));

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/functional-programming/sort-an-array-alphabetically-using-the-sort-method

You are not returning newArr.

Two things
1.while sort works on array in place the function is still expecting a return value

2.One of the examples (reverseAlpha) leading up to this challenge has an issue that surfaced after a recent version update to Chrome. A solution based on that example will no longer pass the challenge.

The compare function should return a number and sort order will be determined depending on whether the returned number is positive, negative or zero. In the past most browsers would also accept true or false as return values so many examples including the one provided for this challenge show a boolean return value.

// better solution works like this
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Description
function compare(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}

Chrome recently fixed this oversight which has now broken sort compare functions that rely on a boolean return value. FCC has a fix for the example code but that does not appear to have been pushed to the site yet.

2 Likes