Problem when ordering an array with sort ()

3

One of these occurs when I want to sort an 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 the one I'm working on (with over 300 occurrences) has been the same. 115 appears before 2, for example.

    
asked by anonymous 16.03.2016 / 15:36

3 answers

8

To order precise numbers to pass a method comparison function.

Test with

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

The return of this function is what indicates to the method the position of the element in relation to what is being compared.

That is:

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: link

As @bigown specified the comparison the method does (without giving it a function) does not what do you think The official specification is :

  

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

In other words, when a function is not passed, what is done is at your browser's convenience. In MDN it is said that the values will be treated as String and I think this is what the biggest pare of browsers does. ( read more at MDN in English here )

    
16.03.2016 / 15:42
4

JavaScript treats 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; });
document.body.innerHTML += a
    
16.03.2016 / 15:42
0

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

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

Or it could also do this:

var a = [44,7,5,6,4,2,1];
a.sort(function(a, b){
  return a > b;
});
document.write(a);
    
16.03.2016 / 15:47