JavaScript Learning notes: Array of sort () and reverse () methods

Source: Internet
Author: User

In the actual business, it is often time to reorder the well-defined arrays. With two methods in JavaScript, you can sort operations on an array. These two methods are the same sort() as reverse() . Learn the knowledge of these two methods today.

sort()Method

sort()method to sort the elements of the array in situ and return the arrays. By default, the sort() method is to arrange the array items in ascending order. That is, the smallest value is at the front, and the largest value is arranged at the last face. To implement sorting, the sort() method invokes the transformation method for each array item toString() , and then compares the resulting string to determine how to sort.

Let's look at a simple example:

var arr = [‘hello‘,‘jame‘,‘Jack‘,‘dog‘]; // 定义一个数组console.log(arr.sort()); // ["Jack", "dog", "hello", "jame"]

As mentioned earlier, the sort() method does not invoke any parameters, it is arranged in ascending order, that is, in alphabetical sequence, so we see the result is also correct.

Next, look at an example of the array arrangement of a number:

var arr = [1,5,10,22]; // 定义一个数组console.log(arr.sort()); // [1, 10, 22, 5]

Visible, even if the order of the arrays in the example does not have any problems, the sort() order is not correct after the method has been reordered on an array of groups. What is the reason for this?

Check the relevant documentation to know, sort() method: If the argument is omitted, the array item will first convert its value to a string based on the function to be compared, to be compared by toString() Unicode, and then sorted according to this. as in the previous example, "Jack" is in front of "dog". When numbers are sorted, "5" appears after "10" and "22" because they are first converted to strings, and "10" and "22" are higher than "5".

We can use it charCodeAt() to verify that:

"Jack".charCodeAt() ==> 74"dog".charCodeAt()  ==> 100"5".charCodeAt() ==> 53"10".charCodeAt() ==> 49"22".charCodeAt() ==> 50

In this way, this is not the best solution. Fortunately, the sort() method can accept a comparison function compareFunction as a parameter so that we specify which value is in front of which value.

If indicated compareFunction , the array is sorted by the return value of the call to the function. The comparison function compareFunction receives two parameters a b , and a b is two elements that will be compared:

    • compareFunction(a,b) The returned value 0 is less than: then a less, that is b , a in b front of the line
    • compareFunction(a,b) The returned value is 0 greater than: then a it is greater, that is b , the a b back of the line
    • compareFunction(a,b) The returned value equals 0 : Then a equals b , that is a , b the position remains the same.

compareFunction(a,b)Function:

function compareFunction (a, b) { if (a < b) { return -1; // a排在b的前面 } else if (a > b) { return 1; // a排在b的后面 } else { return 0; // a和b的位置保持不变 }}

This function can be applied to most data types, as long as the compareFunction(a,b) function is passed as a parameter to the sort() method. Due to the previous example:

var arr = [1,5,10,22]; // 定义一个数组arr.sort(compareFunction); // 将compareFunction函数作为参数传给 sort()console.log(arr); // [1, 5, 10, 22]

arrthe array remains in the correct ascending order. In fact, it can be arranged in descending order by an compareFunction(a,b) array, only need to compareFunction adjust the return value of the function:

function comparefunction  (A, b) {if (a < b) {return 1; //a row behind B} else if (a > B) {return-1 ; //a row in front of B} else {return 0; //A and B keep position unchanged}} var arr = [1, 5, 10, 22]; //defines an array arr.sort (comparefunction); //passes the Comparefunction function as a parameter to sort () Console.log (arr); //[5, 1]            

Note: compareFunction(a, b) You must always return the same comparison result for the same input, otherwise the result of the sort will be indeterminate.

It also says that sort() when a method passes in a compareFunction(a,b) parameter, the value returned may be 3 one, so the following is an incorrect notation:

< span class= "keyword" >function comparefunction Span class= "params" > (A, b) {return a < b;} var arr = [21, 0, 3, 11, 4, 5, 6, 7, 8, 9, 10];arr.sort (comparefunction); Console.log (arr); span class= "comment" >//[5, 9, 8, 7, 6, 4, 3, 0]         

The possible result is that [5, 21, 11, 10, 9, 8, 7, 6, 4, 3, 0] this is not the correct result, because return a < b only two values are returned true or false , equivalent 1 or 0 , not -1 .

valueOf()you can use a simpler comparison function for a numeric type or for a method to return an object type of a numeric type.

Ascsort (A, b) passed to sort (), array of numbers in ascending orderfunction Ascsort (A, b) {//A and B are contiguous two array items in the array //if return-1, indicates that a is less than b,a arranged in front of b //if return 1, means A is greater than b,a arranged at the back of B //if return 0, the position of a equals B,a and B remains the same}//Dessort (A, b) passed to sort (), numeric array in descending order functiondessort  (A, b) { //A and B are contiguous two array items in the array return b-a; //if return-1, indicates that B is less than a a, arranged in front of a //if return 1, indicating B is greater than A, B is arranged behind the a //if return 0 means B equals a, the position of B and a remains the same}           

Let's see if the result is the result we want:

var arr = [1,4,10,3], arr2 = [100,12,99,3,2]; //定义数组arr.sort(ascSort); // 将ascSort函数传给sort()arr2.sort(desSort); // 将desSort函数传给sort()console.log(arr); // [1, 3, 4, 10]console.log(arr2); // [100, 99, 12, 3, 2]
Character array arrangement

Create a string array and sort() reorder the strings using:

var stringArray = [‘blue‘, ‘Humpback‘, ‘Beluga‘];stringArray.sort();console.log(‘字符串数组stringArray:‘ + stringArray);

Results from Chrome output:

字符串数组stringArray:Beluga,Humpback,blue
Array of numeric strings

After creating a numeric string array, the array is sorted, and the numeric arrays are specified with the result of not specifying the comparison function:

var numericStringArray = [‘80‘, ‘9‘, ‘700‘];function compareFunction (a, b) { return a - b;}console.log(‘不指定比较函数的数字字符串数组排列:‘ + numericStringArray.sort());console.log(‘指定比较函数的数字字符串数组排列:‘ + numericStringArray.sort(compareFunction));

Results from Chrome output:

不指定比较函数的数字字符串数组排列:700,80,9指定比较函数的数字字符串数组排列:9,80,700
Array of numbers

After creating a numeric array, the array is sorted, and the numeric arrays are specified with the result of not specifying the comparison function:

var numberArray = [80, 9, 700];function compareFunction (a, b) { return a - b;}console.log(‘不指定比较函数的数字数组排列:‘ + numberArray.sort());console.log(‘指定比较函数的数字数组排列:‘ + numberArray.sort(compareFunction));

Results from Chrome output:

不指定比较函数的数字字符串数组排列:700,80,9指定比较函数的数字字符串数组排列:9,80,700
Mixed array of numeric and numeric strings

Creates a numeric and numeric string after the mixed array is sorted, comparing the array with the result of specifying no comparison function:

var mixedNumericArray = [‘80‘, ‘9‘, ‘700‘, 40, 1, 5, 200];function compareFunction (a, b){ return a - b;}console.log(‘不指定比较函数的数组排列:‘ + mixedNumericArray.sort());console.log(‘指定比较函数的数组排列‘ + mixedNumericArray.sort(compareFunction));

Results from Chrome output:

不指定比较函数的数组排列:1,200,40,5,700,80,9指定比较函数的数组排列1,5,9,40,80,200,700
Array of numbers in random order

In addition to arranging the array of numbers in ascending or descending order, you can define a random function that implements the random arrangement of the array. The defined random function returns a positive or negative number, and the table passes a random function to the sort() method, at which point sort() the method determines the position before the two value, based on the positive negative numbers returned by the random function.

var randomArray = [9,0,23,8,3,5];function randomSort(a, b) { return Math.random() - 0.5;}console.log(randomArray.sort(randomSort));// [8, 5, 9, 0, 23, 3]// [8, 3, 5, 0, 23, 9]// [8, 5, 0, 3, 9, 23]
Object array Arrangement

For arrays of objects, we also need to write a constructor first:

function Objectsort(Property, DESC) {Descending arrangementif (DESC) {Returnfunction (A, B) {Return (A[property] > B[property])? -1: (A[property] < B[property])?0 [0; } }Returnfunction  (A, b) {return (A[property] < B[property])? -1: (A[property] > B[property])? 1: 0;} var myArray = [{29}, { "Age": 24}, { "Age": 39}]console.log (Myarray.sort (objectsort true)); //in descending order of name in Object            

Look at the results before and after the chrome output:

Also, simply change the value of the parameter in the comparison function to the array to be sorted in objectSort() desc descending order flase object of the specified property attribute:

console.log(myArray.sort(objectSort(‘age‘,false))); //按objcet中的age升序排列

Pre and post results for chrome output:

In addition, there is a comparison function for it, as shown below:

function Dynamicsort(property) {var SortOrder =1; if (property[0] = =  "-") {SortOrder =-1; property = Property.substr (1); return  Function  (A, b) {var result = (A[property] < B[property])? -1: (A[property] > B[property])? 1: 0; return result * sortOrder;}} Console.log (Myarray.sort (Dynamicsort (//in ascending order Console.log (Myarray.sort (dynamicsort //in descending order              

The

above describes sorting by an attribute, but many times you want to sort by multiple attributes, then the comparison function needs to be adjusted:

function  Dynamicsortmultiple () {var props = arguments; return  function  (obj1, obj2) { span class= "keyword" >var i = 0, result = 0, numberofproperties = props.length; while (result = = 0 && i < numberofproperties) {result = Dynamicsort (Props[i]) (Obj1, OBJ2); i++; } return result;}} Myarray.sort (Dynamicsortmultiple ( '-age '));      
reverse()Method

reverse()method is relatively much simpler, it is used to reverse the position of an element in an array and return a reference to the array. For example, we have an array:

var myArray = ["Airen","W3cplus","Blog"];console.log(myArray.reverse()); // ["Blog", "W3cplus", "Airen"]
Summarize

This article mainly introduces the ordering method of the element items in the array. And the main details are the sort() methods. By sort() passing different comparison functions to a method, we can implement string arrays , arrays of numbers , mixed arrays of numeric and numeric strings , arrays of objects , and so on in order ( ascending or descending ) Arranged.

JavaScript Learning notes: Array of sort () and reverse () methods

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.