Problem sorting an array with Sort()

Asked

Viewed 603 times

4

One of them occurs when I wish to order a array number.

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 array well small, but what I am working on(with more than 300 occurrences) has happened the same. 115 appears before 2, for example.

  • There are several websites where you can find tutorials and practical examples of Javascript. For the ordering case you can see here: http://www.w3schools.com/jsref/jsref_sort.asp

3 answers

9


To sort 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 in relation to what is being compared.

That is to say:

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

Like the @Maniero indicated the comparison the method makes (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 will of the browser. The MDN states that the figures will be treated as String and I think that’s what the biggest stop browsers ago. (read more on MDN in English here)

6

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 in the Github for future reference.

1

You can do as follows to order correctly by passing a function of callback as a parameter for 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 do it that way:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.