Sort array objects in js

Source: Internet
Author: User
Tags sorted by name

I. sort arrays by using sort () in common array sorting js. The sort () method has an optional parameter, which is a function used to determine the order of elements. If this parameter is omitted, the elements in the array are sorted in the ASCII character order. For example, var arr = ["a", "B", "A", "B"]; arr. sort (); console. log (arr); // ["A", "B", "a", "B"] Because the ASCII values of letters A and B are 65 and 66, the values of a and B are 97 and 98 respectively. Therefore, the output result is ["A", "B", "a", "B"]. What if the array element is a number? Var arr = [15, 8, 25, 3]; arr. sort (); console. log (arr); // [15, 25, 3, 8] The result is [15, 25, 3, 8]. In fact, the sort method calls the toString () method of each array item to obtain the string and then sort the string. Although the value is 15 to 3, when comparing strings, "15" is placed before "3. Obviously, this result is not what we want. In this case, the parameter of the sort () method plays a role. We call this parameter A comparison function. The comparison function receives two parameters. If the first parameter is located before the second parameter, a negative number is returned. If the two parameters are equal, 0 is returned, if the first parameter is located after the second parameter, a positive number is returned. Example: copy the code var arr = [23, 9, 4, 78, 3]; var compare = function (x, y) {// compare the function if (x <y) {return-1;} else if (x> y) {return 1 ;}else {return 0 ;}} console. log (arr. sort (compare); copy the code to [3, 4, 9, 23, 78] and return the expected result. To sort by descending order, write the comparison function as follows: copy the code var compare = function (x, y) {if (x <y) {return 1 ;} else if (x> y) {return-1;} else {return 0 ;}} copy the code. We can't use the comparison function to compare the order of strings and numbers that cannot be converted to numbers: var arr = ["B", 5]; console. log (arr. the result of sort (compare) is ["B", 5]. Because the comparison function converts a string to a number before comparison, string B cannot be converted to a number, so it cannot compare the size. However, when a comparison function is not used, the ASCII value is compared, so the result is [5, "B"]. 2. Sorting of array objects if the array items are objects, we need to sort the arrays according to a certain attribute of the array items. What should we do? In fact, it is similar to the previous comparison function: copy the code var arr = [{name: "zlw", age: 24 },{ name: "wlz", age: 25}]; var compare = function (obj1, obj2) {var val1 = obj1.name; var val2 = obj2.name; if (val1 <val2) {return-1;} else if (val1> val2) {return 1 ;}else {return 0 ;}} console. log (arr. sort (compare); copy the code output result to [Object {name = "wlz", age = 25}, Object {name = "zlw", age = 24}], we can see that the array has been sorted by name attribute. We can rebuild the above comparison function: copy the code var compare = function (prop) {return function (obj1, obj2) {var val1 = obj1 [prop]; var val2 = obj2 [prop]; if (val1 <val2) {return-1;} else if (val1> val2) {return 1 ;}else {return 0 ;}}} if you want to sort the code by age, arr. sort (compare ("age. However, when sorting the age attribute, you must note that if the value of the age attribute is a number, the sorting result will be what we want. However, in most cases, the attribute value of the data we transmit from the server is a string. Now I want to change the above array to var arr = [{name: "zlw", age: "24" },{ name: "wlz", age: "5"}]; you can see that I changed the age attribute from number to string, and the age value of the second array item to "5 ". Call arr again. after sort (compare ("age"), the result is: [Object {name = "zlw", age = "24"}, Object {name = "wlz ", age = "5"}] Our expectation is that 5 is at the top of 25, but the result is not. This is because when two numeric strings are relatively large, their ASCII values are compared. The comparison rules are as follows: starting from the first character, sequentially backward until different characters appear, the size is determined by the ASCII value of the first character. Therefore, when "24" and "5" are relatively large, compare the ASCII values of "2" and "5" first. Obviously, the ASCII Value of "2" is smaller than that of "5, determine the sorting order. Now, we need to make some modifications to the comparison function: copy the code var compare = function (prop) {return function (obj1, obj2) {var val1 = obj1 [prop]; var val2 = obj2 [prop]; if (! IsNaN (Number (val1 ))&&! IsNaN (Number (val2) {val1 = Number (val1); val2 = Number (val2);} if (val1 <val2) {return-1 ;} else if (val1> val2) {return 1 ;}else {return 0 ;}}copy the code in the comparison function, first convert the Compare property value to the Number (val1) pass again! IsNaN (Number (val1) determines whether the converted value is a Number (possibly NaN). If the converted value is a Number, it compares the converted value, in this way, we can get the desired result and call arr. sort (compare ("age"): [Object {name = "wlz", age = "5"}, Object {name = "zlw ", age = "24"}] we can see that it is indeed sorted in the correct way. This article is all about the basics and has no technical knowledge. It is just recently encountered a problem in sorting array objects in the project. So I will write it here to share it with you, I believe it will always help some friends.

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.