educative.io

Educative

Javascript - Why do you need (a, b) => a - b in the Sort function?

Why do you need (a, b) => a - b in the Sort function? When I remove the comparator function I get the same answer but the triplets are arranged in a different order but still the correct values.

Hi @Francis_Obiozor,

.sort() takes a comparison function as a parameter. This is what the sorting algorithm uses repeatedly to compare two elements in the array and decide which one goes to the left of the array and which goes to the right.

If you’re sorting numbers in ascending order, the smallest goes to the left. If you’re sorting in descending order, the smallest goes to the right. The function needs to return -1 for a to be sorted to the left of b , 1 to be sorted to the right of b and 0 to be considered equal.