A summary of various methods of JavaScript array ordering

Source: Internet
Author: User
Tags array sort arrays javascript array

Order of singular groups

Sort () function

The sort method of an array object can rearrange the array elements in a certain order. Usually, they are arranged in the order of subtitles. When sort () is used, the comparison function is executed each time the two elements are compared, and two elements are passed as arguments to the comparison function. The comparison function has the following two return values.

1, if the return value is greater than 0, swap the position of two elements
2. If the return value is less than or equal to 0, the operation is not performed.

JavaScript code

Example 1

The following array is assumed:

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 arrays by price by the following methods:

The code is as follows Copy Code

Homes.sort (function (a,b) {return parsefloat (A.price)-parsefloat (B.price)});

Ordering of elements in a single array

The code is as follows Copy Code

<script type= "Text/javascript" >
function Sort_desc (str)//descending array of functions
{
Str.sort (function compare (a,b) {return b-a;}); /is the descending of the K element in the object of 1 in the array
return str;
}
function Sort_asc (str)//Array Ascending
{
Str.sort (function compare (a,b) {return a-b;}); /refers to the ascending of the K element in an object of 1 in the array
return str;
}
var tt=[4,10,8,98,2];
var bb=[];
Bb=sort_desc (TT);
document.write (bb+ "* * Descending output");
var cc=[89,2,100,5];
var dd=[];
DD=SORT_ASC (CC);
document.write ("document.write (dd+ "* * Ascending output");
</script>


the sort of two-dimensional array.

1, sorted by numerical value

Suppose you have the following array

The code is as follows Copy Code

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

Here, if we're going 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 function of the comparison function here? The array, in turn, copies the elements of the array to x,y, for example, first assign arr[0] to x,arr[1] and then use x[0]–y[0], depending on the value returned, if it returns a number greater than 0, then the x in the array is placed behind the Y, and if 0 is returned, Less than 0 puts X in front of y, then the first one is sorted after the following two, until the entire array sort completes. This is the default ascending comparison function, and if you want to sort in descending order, simply change the comparison and change to return y[0]–x[0], where we x[0 the order by the first column, where we can sort by other columns. The sorting here defaults to modifying the ARR array structure, so sorting the arr is an array in ascending order of the first column.

2, sorted by string

Sorted by string, we can use the Localecompare method provided by JS,
Localecompare function: Compares two strings in a local-specific order.
The use rule for the Localecompare method is Stringobject.localecompare (target), and if Stringobject is less than target, Localecompare () returns a number less than 0. If the stringobject is greater than target, the method returns a number greater than 0. If two strings are equal, or if there is no difference based on local collations, the method returns 0, and the comparison uses local rules, which mean that the local rules are sorted by using the underlying rules of the operating system to sort the local characters. The comparison, by default, such as the greater-than number, is simply a comparison of the number of two-character Unicode, which is inconsistent with many languages.
Like what

The code is as follows Copy Code

var arr = [['], ' country '], [' Ah ', ' '], [' Oh ', ']];
Arr.sort (function (x, y) {
Return X[0].localecompare (y[0]);
});

The result is sorted by the phonetic alphabet of the text in the first column, if you have English, the default is to put English in front, if it is pure English, will be alphabetical, uppercase in the lower case, so you can achieve the sort of string, including Chinese and English mixed row. As to the descending order, the method is the same as above, changed to return Y[0].localecompare (X[0]); Can.

Array go heavy, sort, look for index

The code is as follows Copy Code

Array to weight
Array.prototype.distinct = function () {
var filtered= [];
var _a = {};
for (var i = 0;i<this. length;i++) {
if (!_a[this[i]]) {//if already available, no longer added
_a[this[i]] = 1;
Filtered.push (This[i])
}
}
return filtered;
};

Finding indexes by the method of binary Division
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 = [10,15,3,4,5,6,7,8,9,3,8,9];
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

Face questions encountered

Given An array of may contain nested arrays, return a flattened array. Input and out put are illustrated as follows.

Sorts output that contains nested arrays. The * part is the code that needs to be written out.

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 topic is clearly supposed to be solved by recursion: (Revise thanks @felix021 remind ...)

  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 an in object) {
    if (typeof (object) = = ' object ') { br>       Loop (Object[a]);
   }else{
      out.push (Object[a]);
   }
& nbsp
}
Console.log (out);

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.