Summary of various methods for sorting Javascript Arrays

Source: Internet
Author: User

There are many sorting methods for Javascript arrays. js itself provides a large number of data sorting functions. In addition to using it to sort data, other custom sorting methods are also introduced.

Sort by single array

Sort () function

The sort method of array objects can rearrange array elements in a certain order. Generally, subtitles are arranged in sequence. When sort () is used for sorting, the comparison function is executed every time two elements are compared, and the two elements are passed as parameters to the comparison function. The comparison function has the following two return values.

1. If the return value is greater than 0, the positions of the two elements are exchanged.
2. If the return value is less than or equal to 0, no operation is performed.

JavaScript code

Example 1

Suppose there are the following Arrays:

The Code is as follows: Copy code

Var homes = [{
"H_id": "3 ",
"City": "Dallas ",
"State": "TX ",
"Zip": "75201 ",
"Price": "162500"
},{
"H_id": "4 ",
"City": "Bevery Hills ",
"State": "CA ",
"Zip": "90210 ",
"Price": "319250"
},{
"H_id": "5 ",
"City": "New York ",
"State": "NY ",
"Zip": "00010 ",
"Price": "962500"
}];

You can sort the array by price using the following method:

The Code is as follows: Copy code

Homes. sort (function (a, B) {return parseFloat (a. price)-parseFloat (B. price )});

Sort elements in an array

The Code is as follows: Copy code

<Script type = "text/javascript">
Function sort_desc (str) // a function for descending order of Arrays
{
Str. sort (function compare (a, B) {return B-a;}); // indicates the descending order of the k elements in the object 1 in the array.
Return str;
}
Function sort_asc (str) // function for ascending Array
{
Str. sort (function compare (a, B) {return a-B ;}); // indicates the ascending order of the k elements in the object 1 in the array.
Return str;
}
Var tt = [4, 10, 8, 98, 2];
Var bb = [];
Bb = sort_desc (tt );
Document. write (bb + "*** output in descending order ");
Var cc = [89,2, 100,5];
Var dd = [];
Dd = sort_asc (cc );
Document. write ("Document. write (dd + "*** output in ascending order ");
</Script>


Sort two-dimensional arrays.

1. sort by value

Suppose there are the following Arrays:

The Code is as follows: Copy code

Var arr = [[1, 2, 3], [7, 2, 3], [3, 2, 3];

Here, if we want to sort by the first column of each sub-array, we can define a comparison function:

The Code is as follows: Copy code

Arr. sort (function (x, y ){
Return x [0]-y [0];
});

What is the role of the comparison function here? In fact, arrays copy array elements to x and y in sequence. For example, arr [0] is first assigned to x and arr [1] to y, then, use x [0]-y [0]. Based on the returned value, if the returned number is greater than 0, Put x in the array after y, if the return value is 0, it will not change. If the return value is less than 0, x will be placed in front of y. After the first one is sorted, the following two orders will be performed until the entire array is sorted. This is the default comparison function in ascending order. To sort data in descending order, you only need to change the comparison method to return y [0]-x [0, here we use x [0] To sort by the first column. Here we can also sort by other columns. By default, the array structure of arr is modified. After sorting, arr is an array in ascending order of the first column.

2. sort by string

To sort strings, we can use the localeCompare method provided by js,
LocaleCompare: Compares two strings in a specific local order.
The use rule of the localeCompare method is stringObject. localeCompare (target). If the stringObject is smaller than the target, localeCompare () returns a number smaller than 0. If the value of stringObject is greater than target, this method returns a value greater than 0. If the two strings are equal, or there is no difference according to the local sorting rules, this method returns 0, the comparison uses the local rule, A local rule means that the operating system is used to sort the rules for sorting local characters. By default, a comparison such as greater than a number only compares the unicode size of two characters, it is inconsistent with many languages.
For example

The Code is as follows: Copy code

Var arr = [['zhong', 'Guo '], [' Ah ','], ['Oh', '];
Arr. sort (function (x, y ){
Return x [0]. localeCompare (y [0]);
});

The results are sorted by the pinyin characters in the first column. If English is included, the English letters are placed first by default. If the English is pure, the results are sorted alphabetically, in this way, strings can be sorted in uppercase at the end of lower case, including Chinese and Chinese-English hybrid sorting. To sort data in descending order, change the method to return y [0]. localeCompare (x [0.

Array deduplication, sorting, search for Indexes

 

The Code is as follows: Copy code

// Array deduplication
Array. prototype. distinct = function (){
Var filtered = [];
Var _ a = {};
For (var I = 0; I <this. length; I ++ ){
If (! _ A [this [I]) {// if it already exists, it will not be added.
_ A [this [I] = 1;
Filtered. push (this [I])
}
}
Return filtered;
};

// Search for indexes using the binary method
Function search (arr, item, lower, upper ){
Lower = lower | 0;
Upper = upper | arr. length-1;
If (lower = upper ){
If (item = arr [upper]) {
Return upper;
} Else {
Return-1;
}
} Else {
Var middle = parseInt (lower + upper)/2 );
If (item> a [middle]) {
Return search (arr, item, middle + 1, upper );
} Else {
Return search (arr, item, lower, middle );
}
}

}

Var a = [,];
A = a. distinct (); // [10, 15, 3, 4, 5, 6, 7, 8, 9]
A. sort (function (a, B) {return a-B;}); // sort [3, 4, 5, 6, 7, 8, 9, 10, 15]
Alert (search (a, 9); // 6

Interview Questions

Given an array that may contain in nested arrays, return a flattened array. Input and out put are stored strated as follows.

Sorts and outputs nested arrays. * Indicates the code to be written.

The Code is as follows: Copy code

Var input = [{a: 'A'}, 'B', ['C', 'D'], ['E', ['F'], 'G'];
Function flatten_array (arr ){
Var out = [];
*******;
Return out;
}


This question should be solved recursively: (modify thanks @ felix021 to remind me ...)

The Code is as follows: Copy code

Var input = [{a: 'A'}, 'B', ['C', 'D'], ['E', ['F'], 'G'];
Var out = [];

Loop (input );

Function loop (object ){
For (var a in object ){
If (typeof (object) === 'object '){
Loop (object [a]);
} Else {
Out. push (object [a]);
}
}
}
Console. log (out );

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.