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:'tom',age:18}, {name:'lucy',age:24}, {name:'jhon',age:17}, ]; console.log(users.sort(compareFunc('age'))); // 输出结果 [{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, 'text/xml'); var userElements=xmlDoc.getElementsByTagName('user')); // 4.userElements类数组对象转换成数组再排序 var userElements=Array.prototype.slice.call(xmlDoc.getElementsByTagName('user')); var _userElements=userElements.sort(compareFunction('age')); // 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

The bottom layer of the C++sort function uses merge sort, its complexity is O(nlogn), and provides different sorting algorithm choices, including quick sort, heap sort and stable sort.

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese
