Home  >  Article  >  Web Front-end  >  The sort method in JavaScript that you don’t know

The sort method in JavaScript that you don’t know

angryTom
angryTomforward
2019-11-29 14:13:372835browse

The sort method in JavaScript that you don’t know

In daily business development, array (Array) is a data type we often use, so sorting arrays is also very common. In addition to using the method of looping through the array to arrange Data is arranged using the native method sort in JS arrays (yes, I prefer the power of native JS).

[Recommended courses: JavaScript video tutorial]

1. For example,

can be used directly in an array The sorting methods are: reverse() and sort(). Because the reverse() method is not flexible enough, the sort() method is introduced. By default, the sort() method sorts the array in ascending order.

var arr=[1,3,5,9,4];
console.log(arr.sort());
// 输出: [1, 3, 4, 5, 9]

At this time, I found that the data was arranged from small to large, no problem; so I changed the array to: var arr=[101,1,3,5,9,4,11];, and then called sort () method prints the sorting results.

var arr=[101,1,3,5,9,4,11];
console.log(arr.sort());
// 输出: [1, 101, 11, 3, 4, 5, 9]

At this time, it was found that arrays 101 and 11 were all ranked in front of 3. This is because the sort() method will call the toString() transformation method of the array, and then compare the obtained strings to determine How to sort? Even if each item in the array is a numerical value, the sort() method compares strings.

So how are strings sorted? They are sorted from small to large according to the unicode encoding of the strings. Next we try to print out the unicode encoding of each item in the array to take a look.

...
// 转码方法
function getUnicode (charCode) {
    return charCode.charCodeAt(0).toString(16);
}
// 打印转码
arr.forEach((n)=>{
  console.log(getUnicode(String(n)))
});
// 输出: 31 31 31 33 34 35 39

I was surprised to find that the unicode encoding of the strings 1,101,11 are all 31

2. Pass in the comparison function in the specified order

or above It is found that the sort() method is not sorted in the order we want, so how to solve it? The sort() method can receive a comparison function as a parameter to specify which value is in front of which value.

The comparison function (compare) receives two parameters. If the first parameter is before the second parameter, it returns a negative number. If the two parameters are equal, it returns 0. If the first parameter is after the second parameter, it returns then returns an integer.

function compare(value1,value2){
  if (value1 < value2){
    return -1;
  } else if (value1 > value2){
    return 1;
  } else{
    return 0;
  }
}

We pass the comparison function to the sort() method, and then arrange the arr array. The print result is as follows:

var arr=[101,1,3,5,9,4,11];
console.log(arr.sort(compare));
// 输出: [1, 3, 4, 5, 9, 11, 101];

It can be found that there is no problem in sorting from small to large.

3. Sorting of object arrays

The sort() method sorts the numeric array by passing in a comparison function, but in development, we will sort an object array Sort by a certain attribute, such as id, age, etc., so how to solve it?

To solve this problem: we can define a function, let it receive an attribute name, and then create a comparison function based on this attribute name and return it as a return value (functions in JS can be used as values, Not only can you pass a function to another function like a parameter, but you can also return a function as the result of another function. There is a reason why functions are first-class citizens in JS. It is indeed very flexible.), the code is as follows .

function compareFunc(prop){
  return function (obj1,obj2){
    var value1=obj1[prop];
    var value2=obj2[prop];
    if (value1 < value2){
        return -1;
    } else if (value1 > value2){
        return 1;
    } else{
        return 0;
    }
  }
}

Define an array users, call the sort() method and pass in compareFunc(prop) to print the output results:

var users=[
    {name:&#39;tom&#39;,age:18},
    {name:&#39;lucy&#39;,age:24},
    {name:&#39;jhon&#39;,age:17},
];
console.log(users.sort(compareFunc(&#39;age&#39;)));
// 输出结果
[{name: "jhon", age: 17},
{name: "tom", age: 18},
{name: "lucy", age: 24}]

By default, when the sort() method is called without passing in the comparison function , the sort() method will call the toString() method of each object to determine their order. When we call the compareFunc('age') method to create a comparison function, the sorting is sorted according to the age attribute of the object.

4. Sorting of XML nodes

Although many background return data are now in JSON format, it is very lightweight and easy to parse. However, there was a previous project because all the data returned by the background were XML strings. After the front-end got the data, it had to be serialized, and some needed to be sorted. The previous sorting was to convert XML into array objects for sorting. There is no problem in doing so. , but I feel that the code is very redundant and troublesome. Later, I suddenly thought that the xml obtained was also an array-like object. If the array-like object was converted into an array, wouldn't it be possible to sort directly?

// 1.模拟后端返回的XML字符串
var str=`
<root>
  <user>
    <name>tom</name>
    <age>18</age>
  </user>
  <user>
    <name>lucy</name>
    <age>24</age>
  </user>
  <user>
    <name>jhon</name>
    <age>17</age>
  </user>
<root>
`   
// 2.定义比较函数
function compareFunction(prop){
  return function (a, b) {
      var value1= a.getElementsByTagName(prop)[0].textContent;
      var value2= b.getElementsByTagName(prop)[0].textContent;
      if (value1 < value2){
        return -1;
      } else if (value1 > value2){
        return 1;
      } else{
        return 0;
    }
  }
}
// 3.xml字符串转换成xml对象
var domParser = new DOMParser();
var xmlDoc = domParser.parseFromString(str, &#39;text/xml&#39;);
var userElements=xmlDoc.getElementsByTagName(&#39;user&#39;));
// 4.userElements类数组对象转换成数组再排序
var userElements=Array.prototype.slice.call(xmlDoc.getElementsByTagName(&#39;user&#39;));
var _userElements=userElements.sort(compareFunction(&#39;age&#39;));
// 5.打印排序后的结果
_userElements.forEach((user)=>{
  console.log(user.innerHTML);
});

Print the sorted results

It can be found that the XML nodes have been sorted from small to large according to age.

5. Summary

The sort method of JS array makes the sorting much more flexible because of the incoming comparison function. It can also be sorted according to time, the first letter of Chinese pinyin, etc. Etc., we just need to remember to explicitly compare the attribute values ​​​​of the two objects by passing in the comparison function, and determine the sorting order of the objects by comparing the attribute values. I also encountered problems at work and found new ideas to solve them. This is a brief summary. If there are any shortcomings, please correct me.

Reference materials:

"JavaScript Advanced Tutorial"

This article comes from the js tutorial column, welcome to learn!

The above is the detailed content of The sort method in JavaScript that you don’t know. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete