Problem sorting an array with sort()

One of these occurs when I want to sort a array of numbers.

Ex:

var a = [44,7,5,6,4,2,1];
a.sort();
console.log(a);

The expected result would be:

[1, 2, 4, 5, 6, 7, 44], but what is always returned to me is [1, 2, 4, 44, 5, 6, 7].

This is a very small array, but what I'm working on(with more than 300 occurrences) has happened the same. 115 appears before 2, for example.

Author: Maniero, 2016-03-16

3 answers

To order numbers you need to pass a comparison function to the method.

Test with

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

The Return of this function is what indicates to the method the position of the element relative to what is being compared.

I.e.:

var a = [44,7,5,6,4,2,1];
a = a.sort(function(a, b) {
   return a - b;
});
console.log(a); // dá [1, 2, 4, 5, 6, 7, 44]

JsFiddle: https://jsfiddle.net/e3gx7dgv/1

As @Maniero indicated the comparison that the method does (without passing it a function) does not do what you think. the official specification is :

If comparefn is not undefined and is not a consistent comparison function for the elements of this array (see below), the behaviour of sort is implementation-defined.

That is, when a function is not passed what is done is at the discretion of browser . In MDN it is mentioned that the values will be treated as String and I think that is what the biggest stop of the browsers does. (read more at MDN in English here )

 8
Author: Sergio, 2019-09-03 14:09:47

JavaScript treats the elements as string, so the "problem" happens. Solution:

var a = [44, 7, 5, 6, 4, 2, 1];
a.sort(function(a, b) { return a - b; });
console.log(a);

I put on GitHub for future reference .

 5
Author: Maniero, 2019-12-27 12:40:22

You can do the following to sort correctly by passing a function of callback as a parameter to the function sort:

var a = [44,7,5,6,4,2,1];
a.sort(function(a, b) {
  return a - b;
});
document.write(a);
//console.log(a);

Or you could also do it this way:

var a = [44,7,5,6,4,2,1];
a.sort(function(a, b){
  return a > b;
});
document.write(a);
 0
Author: Yure Pereira, 2016-03-16 15:28:46