Functional Programming - Sort an Array Alphabetically using the sort Method

Tell us what’s happening:
Describe your issue in detail here.
I still do not understand this example:

function reverseAlpha(arr) {
  return arr.sort(function(a, b) {
    return a === b ? 0 : a < b ? 1 : -1;
  });
}

reverseAlpha(['l', 'h', 'z', 'b', 's']);

especially this part : ```
return a === b ? 0 : a < b ? 1 : -1;

Can you explain that to me, thank you.

1 means that a is greater than b by the ordering criterion, while -1 means that a is less than b by some ordering criterion. All elements are compared against each other that way until the array is sorted. a === b ? 0 means that if they are equal then they don’t move, and as far as I know you can drop that condition altogether, at least for this piece of code. Btw I just quoted MDN, you might wanna take a look at it. Array.prototype.sort() - JavaScript | MDN
Consider this

let nums = [1, 2, 1, 3]

function sorted(a) {
    return a.sort((a, b) => {
        return a < b ? 1 : -1
    })
}

console.log(sorted(nums))
1 Like

Thank you, but can you tell me what type of function they are using in this code: a === b ? 0 : a < b ? 1 : -1;

That is a ternary operator, it equals to

if (a === b) {
return 0
} else if (a < b) {
return 1 
} else {
return -1
}
1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.