Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting Javascript Array with Chrome?

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!

like image 383
jantimon Avatar asked Dec 28 '09 11:12

jantimon


People also ask

Can you sort an array in JavaScript?

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.

What is the correct method to use in JavaScript sorting arrays?

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.

What sort algorithm does chrome use?

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.

How do you sort an array in ascending and descending order in JavaScript?

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.


2 Answers

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

like image 125
Kobi Avatar answered Sep 22 '22 06:09

Kobi


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

like image 40
KJ Saxena Avatar answered Sep 20 '22 06:09

KJ Saxena