Array sorting in Java Script


1 reply [Last post]
jazz
Offline
Joined: 11/19/2010

In JavaScript, you can sort arrays using the sort method. As the only optional argument method takes a function that determines the sorting rules. If sort is called without arguments, then sorting by ascending values of the elements. Example:
//array
var arr = [0, true, 'John', 'Peter', 56, NaN, false, 13, 'Mike'];
// sorting
arr.sort();
// return [0,13,56,NaN,false,true,John,Mike,Peter]
Sorted array, in which context the method is called, so if you want to keep the original state - make up and sort it.
Functions Sorting

You can customize the sorting method of passing a special sort function. As arguments the function takes two values of the array, which will give the method sort. Function can return the following values

* Positive (1,2,10) if sorting condition is true;
* Negative (-0.1, -3, -20), if sorting condition is false;
* 0 if the compared values are equal.

Performance

At first glance it may seem that sorting in JavaScript unproductively, and web-applications is better to sort the data on the server-side. Small experiment is denied. Be careful in cycles per 100.000 elements may hang your browser!

Sort array c integer values of different lengths:
No data

can overload

The author, in the course of his experiments on his PC (Vista, Pentium Dual 2.2GHz, 2GB RAM) got the following results:
1000 10.000 100.000
IE 7 20-50 ms 200-650 ms buzz
FF 3 1-2 ms 12-30 ms 150-400 ms
Safari 3 2-30 ms * 30-400 ms * 350-5000 ms *
Opera 9.5 2-5 ms 40-75 ms 500-1000 ms
Chrome 1.0 1-2 ms 10-30 ms 100-300ms