Is there a way to sort an array using Chrome?
Using the sort function does not work as seen in this example:
var myArray = [1,4,5,3,2]; myArray.sort ( function( a , b ){ return b>a }); for ( var i = 0; i < myArray.length; i++ ) { document.write( myArray[i] ) }
Firefox / IE / Opera / Safri output: 54321
Chrome output: 53241
jsBin example
Thanks for your time!
JavaScript Array sort()The sort() sorts the elements of an array. The sort() overwrites the original array. The sort() sorts the elements as strings in alphabetical and ascending order.
sort() The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.
Chrome uses a stable sorting algorithm for arrays of length < 10, but for arrays of more than ten items, it uses an unstable QuickSort algorithm. This can lead to unreliable behavior that you might not discover when testing if you don't think to test your code on an array with more than ten items in Chrome.
sort((function(index) { return function(a, b){ return (a[index] === b[index] ? 0 : (a[index] < b[index] ? -1 :1)); }; })(0)); As you can see, it is sorted in ascending order.
The comparer function should return a negative number, positive number, or zero (which is a convention across programming languages).
myArray.sort(function(a, b) { return a-b; });
Full description is here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#description
The behavior of Chrome is correct :)
The ECMA standards require the function being passed to sort() to return a number greater than 0, less than 0 or equal to 0. However, the function you have defined returns true / false. ECMA standards state that for a function which does not behave as expected, the implementation depends on the client.
Read this
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With