Daniel Ortiz
Daniel Ortiz

Reputation: 921

Why does .sort() behave incorrectly when alphabetically sorting some arrays?

There's a weird JavaScript behavior I came across. If I try to sort ['a', 'b','c', 'd', 'e', 'f', 'g', 'h','i', 'j'] with [].sort((a, b) => a > b), it returns the array sorted correctly (in this case, exactly as it was before), but if I add one more item to the array, like:

['a', 'b','c', 'd', 'e', 'f', 'g', 'h','i', 'j', 'k'].sort(
  (a, b) => a > b
)

it returns:

["f", "a", "b", "c", "d", "e", "g", "h", "i", "j", "k"]

Oddly enough, if I add "l" to the array, it returns:

["g", "a", "b", "c", "d", "e", "f", "h", "i", "j", "k", "l"] ('f' now is in the correct place, but 'g' is not o.O)

If I use the .sort method without providing a comparator it sorts correctly, but that's of no use to me, since I'm actually trying to sort an array of objects by a property, like:

[{ firstName: 'Peter' }, { firstName: 'Alfred' }]

Does anyone know why this happens?

Upvotes: 0

Views: 539

Answers (3)

Ye Liu
Ye Liu

Reputation: 8986

The comparison function should return a negative number if a < b, 0 if a = b, and a positive number if a > b, so it should look like this:

(a, b) => {
  if (a < b) {
    return -1;
  }
  if (a > b) {
    return 1;
  }
  return 0;
}

Upvotes: 0

joe_coolish
joe_coolish

Reputation: 7259

The sort() function will use the compareFunction to specify the sort order. If omitted, the array is sorted according to each character's Unicode code point value, according to the string conversion of each element.

Try using something like:

function compareNumbers(a, b) {
  return a - b;
}

Look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort for more information

Upvotes: -1

Pointy
Pointy

Reputation: 414086

Your .sort() comparator function is incorrect. The .sort() comparator should return a negative number when the first value should sort before the second; a positive number when the second should sort before the first; and 0 when they should be considered the same value for ordering purposes.

Your comparator returns true or false, which will be interpreted as 1 or 0. Thus when a is less than b, your comparator tells .sort() that it's the same as b.

Strings have a handy method available that works great for sorting:

['world', 'hello'].sort((a, b) => a.localeCompare(b));

When sorting numbers, you can just return the result of a subtraction operation.

Upvotes: 5

Related Questions