This question already has answers here:
How to sort an array of integers correctly
(32 answers)
Closed 6 years ago.
I have an array having values are 1,10,6,8,7 and I want to sort this using sort() method, It's giving result like this 1,10,6,7,8 rather than 1,6,7,8,10
I wrote code below :
var arr = [1,10,6,8,7];
arr.sort();
document.write(arr);
Can anyone have idea about this?
var scores = [1, 10, 21, 2];
scores.sort(); // [1, 10, 2, 21]
// Watch out that 10 comes before 2,
// because '10' comes before '2' in Unicode code point order.
Refer this link https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
10 is before 2 in unicode. You need to help the sort() function to determine which element is before which.
arr.sort(function(a, b) {
return a - b;
});
From the documentation:
If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in Unicode code point order.
This is why sort on an array of number is "weird": because it compares the string representation of the numbers.
In a unicode point of view: "10" < "2".
You're getting a lexicographical sort (e.g. convert objects to strings, and sort them in dictionary order), which is the default sort behavior in Javascript:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort
Original answer:
https://stackoverflow.com/a/7000924/7462678
According to the Mozilla Developer Network, "The default sort order is according to string Unicode code points.". 10 comes before 2 in Unicode code point order. You would need to pass in a comparison function to the sort function, which would compare the numbers.
Array.prototype.sort - Mozilla Developer Network
Related
This question already has answers here:
How does sort() works in JavaScript?
(4 answers)
Closed 1 year ago.
i am getting a strange result using arr.sort() below is the code
const arr=[1,99,102,121,2,2,3,7]
arr.sort()
console.log(arr)
I am getting the following output
[
1, 1000, 121, 2,
2, 3, 7, 99
]
can someone please explain what is happening and why?
As stated in the docs
The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.
Thus your values are converted to strings first and then compared lexicographic. Ie "101" is less than "2"
If you want to do a numerical sort, you have to provide a compare function
const arr=[1,99,102,121,2,2,3,7]
arr.sort((a,b) => a-b);
console.log(arr);
Array.sort accepts a function as parameter:
compareFunction Optional
Specifies a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value.
You need arr.sort((a,b) => a - b)
This question already has answers here:
How to sort an array of integers correctly
(32 answers)
Closed 5 years ago.
Why is this function returning elements sorted alphabetically rather than numerically? I get the identical results whether I use Number or ParseFloat.
function sortMe() {
var x = ["1.0","2.5", "11.0"];
var y = x.map(Number);
Logger.log(y.sort());
}
Result: 1,11,2.5
Because Array#sort sorts alphabetical, so '11' comes before '2'.
The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.
To overcome this problem, you could use a numerical sort with a callback, like
array.sort(function (a, b) {
return a - b;
});
That's because the default sort order is according to string Unicode code points, no matter what your input is. Your Number are implicitly converted back to strings and then sorted.
Its not that you are unable to pass a numeric array, whatever you pass Array#sort will try to compare on the basis of their unicode representation. Instead pass a comparator, to compare how you want to compare while sorting
y.sort((a,b)=>a-b)
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, with respect to each element's Unicode point value.
Have a look at this example:
var fruit = ['cherries', 'apples', 'bananas'];
fruit.sort(); // ['apples', 'bananas', 'cherries']
var scores = [1, 10, 21, 2];
scores.sort(); // [1, 10, 2, 21]
// Note that 10 comes before 2,
// because '10' comes before '2' in Unicode code point order.
var things = ['word', 'Word', '1 Word', '2 Words'];
things.sort(); // ['1 Word', '2 Words', 'Word', 'word']
// In Unicode, numbers come before upper case letters,
// which come before lower case letters.
This question already has answers here:
How to sort an array of integers correctly
(32 answers)
Closed 6 years ago.
I found that using sort without comparing function would result in wrong answer and I don't know the reason.
var a = [823564440,115438165,784484492,74243042,114807987,137522503,441282327,16531729,823378840,143542612]
a.sort()
a.sort((a,b) => a-b)
The two should give same result in my mind, but they don't. And clearly the latter is correct.
a.sort()
[114807987, 115438165, 137522503, 143542612, 16531729, 441282327, 74243042, 784484492, 823378840, 823564440]
a.sort((a, b) => a-b)
[16531729, 74243042, 114807987, 115438165, 137522503, 143542612, 441282327, 784484492, 823378840, 823564440]
Can anyone tell me the reason behind this?
Per the MDN documentation:
The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points. (Emphasis mine)†
Since you do not supply a function, default sort order is used. Thus, the elements are sorted as if they were strings, versus the latter sort, where it is sorted based on number value.
Because of this, 1 comes before 2, 2 before 3 etc. no matter the number of digits as strings are compared place by place. (See list of unicode characters; since 1 in Unicode is U+0031, it comes before U+0032 and is thus smaller).
In your example, this would mean 115438165 coming before 74243042 although the latter is smaller mathematically. Because the strings are compared place by place, 1 is compared to 7 and is less than, thus yielding the result. For further reading, see lexicographical order.
† This is by specification. See the ECMAScript® 2015 Language Specification, Section 22.1.3.24.1 - Runtime Semantics: SortCompare( x, y ). Here, it explains that if no sorting function is passed, string representations of x and y (found using ToString) are compared.
Read the documentation.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in Unicode code point order. For example, "Banana" comes before "cherry". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in Unicode order.
This question already has answers here:
How to sort an array of integers correctly
(32 answers)
Closed 8 years ago.
I can't seem to figure this one out.
var arr = [2.62, 111.05, 1.05]
arr.sort();
This returns [1.05, 111.05, 2.62], but I'm expecting [1.05, 2.62, 111.05].
How can this be achieved? I've read a bit about writing a custom sort to split the "decimal" but haven't managed to have any success.
By default sorting is alphabetically. You need to pass a function to the sort method
arr.sort(function(a, b){return a-b;});
The sort method compares the items as strings by default. You can specify a comparer function to make the comparison any way you like. This will compare the items as numbers:
arr.sort(function(a, b){ return a - b; });
Note: All numbers in Javascript a double precision floating point numbers, even if they happen to contain an integer value, so integer values and decimal values are not treated differently.
This is the normal behavior for Array.sort() when it isn't given a comparator function. Try this:
var arr = [2.62, 111.05, 1.05];
arr.sort(function(a,b) { return a-b; });
From MDN:
If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in Unicode code point order. For example, "Cherry" comes before "banana". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in Unicode order.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
sort not working with integers?
How to sort number in javascript sort method
Array.sort() doesn't sort numbers correctly
Code:
var x = [40,100,1,5,25,10];
x.sort();
output:
1,10,100,25,40,5
My expected output:
1,5,10,25,40,100
The JavaScript Array .sort() function by default converts the array elements to strings before making comparisons.
You can override that:
x.sort(function(e1, e2) { return e1 - e2; });
(The function passed should return a number that's negative, zero, or positive, according to whether the first element is less than, equal to, or greater than the second.)
I've never seen a rationale for this odd aspect of the language.
According to MDN Array.sort
If compareFunction is not supplied, elements are sorted by converting them to strings and comparing strings in lexicographic ("dictionary" or "telephone book," not numerical) order. For example, "80" comes before "9" in lexicographic order, but in a numeric sort 9 comes before 80.
So you should be doing something like:
function compareNumbers(a, b)
{
return a - b;
}
var x = [40,100,1,5,25,10];
x.sort(compareNumbers);
var x = [40,100,1,5,25,10];
x.sort(function(a,b){return a-b});
It does an alphabetical, ascending sorting (the 1 character is sorted.. 1,1_,1_,2,4_,5) as default and providing a compare function changes that behavior
More info can be found here : http://www.w3schools.com/jsref/jsref_sort.asp