Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't JavaScript sort [5, 10, 1]? [duplicate]

This seems like a simple sort, yet JavaScript is giving an incorrect result.

Am I doing something wrong or is this a language quirk?

[5, 10, 1].sort();

[ 1, 10, 5 ]

like image 239
kabir Avatar asked Jan 09 '14 12:01

kabir


People also ask

Why is sort not working in JS?

This is because sort() needs a callback comparator, and when sort() is used without one, String() acts as the default callback. This is our callback function that will help sort the numbers in the correct and ascending order.

What is the complexity of JavaScript sort?

sort(Object[]) is based on the TimSort algorithm, giving us a time complexity of O(n log(n)).

What is the correct way to sort the numbers in ascending order in JavaScript?

JavaScript Array sort() The sort() sorts the elements as strings in alphabetical and ascending order.

How do I sort JavaScript without mutating?

To sort an array, without mutating the original array:Call the slice() method on the array to get a copy. Call the sort() method on the copied array. The sort method will sort the copied array, without mutating the original.


1 Answers

Javascript sorts alphabetically. This means that "10" is lower than "5", because "1" is lower than "5".

To sort numerical values you need to pass in numerical comparator like this:

function sorter(a, b) {
  if (a < b) return -1;  // any negative number works
  if (a > b) return 1;   // any positive number works
  return 0; // equal values MUST yield zero
}

[1,10, 5].sort(sorter);

Or you can cheat by passing simpler function:

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

[1, 10, 5].sort(sorter);

Logic behind this shorter function is that comparator must return x>0 if a > b, x<0 if a < b and zero if a is equal to b. So in case you have

a=1 b=5
a-b will yield negative(-4) number meaning b is larger than a

a=5 b=1
a-b will yield positive number(4) meaning a is larger than b

a=3 b=3
a-b will yield 0 meaning they are equal
like image 168
lukas.pukenis Avatar answered Sep 17 '22 13:09

lukas.pukenis