Reputation: 15800
I entered the following code into the chrome console.
var array = [25,7,8,41];
array.sort();
It returns [25,41,7,8]
. What's going on?
Upvotes: 4
Views: 2685
Reputation: 300
Sort method sorts items of an array. Sort method by itself interprets items as strings. Since "2" in "25" is a lower number than "7" in "7", it returns that 25 is indexed before 7 for example. In order to sort numbers in ascending order user:
var array = [25,7,8,41];
array.sort(function(a, b){return a-b});
Check this example as well.
Upvotes: 1
Reputation: 7496
Everything in javascript is object by default and when you try to sort it is trying to sort it alphabetically. You have to write your own compare function to sort them numerically check the following code snippet
var array = [25,7,8,41];
array.sort(sortCompare);
function sortCompare(a,b){
return a-b;
}
console.log(array);
Upvotes: 1
Reputation: 463
By default the sort method sorts elements alphabetically. To sort numerically just add a new method which handles numeric sorts (sortNumber, shown below) -
function sortNumber(a,b) {
return a - b;
}
var Array = [25 , 7 , 8 , 41];
Array.sort(sortNumber);
source How to sort an array of integers correctly
Upvotes: 1
Reputation: 8660
The sort() method sorts the items of an array.
The sort order can be either alphabetic or numeric, and either ascending (up) or descending (down).
By default, the sort() method sorts the values as strings in alphabetical and ascending order.
This works well for strings ("Apple" comes before "Banana"). However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".
Because of this, the sort() method will produce an incorrect result when sorting numbers.
If you would like this to be corrected you can write a comparison function as the first parameter passed to the sort method. There is one listed in the reference!
EDIT: Posted here for future cases...
var points = [40, 100, 1, 5, 25, 10];
function myFunction() {
points.sort(function(a, b){return a-b});
console.log(points);
}
Upvotes: 6
Reputation: 13623
To expand on the other answers here with a solution to the problem you are facing-- from MDN's array.sort page:
To compare numbers instead of strings, the compare function can simply subtract b from a. The following function will sort the array ascending (if it doesn't contain Infinity and NaN):
function compareNumbers(a, b) {
return a - b;
}
Upvotes: 0