In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article focuses on "how to use sort in JavaScript". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let the editor take you to learn how to use sort in JavaScript.
In normal business development, Array is the data type that we often use, so the sorting of arrays is also very common. In addition to using the method of looping through the array to arrange the data, use the native method sort in the JS array to arrange (yes, advocate the native power of JS).
1. Give me a chestnut
The methods that can be used to sort the array directly are: reverse () and sort (). Because the reverse () method is not flexible enough, there is a sort () method. By default, the sort () method sorts the array in ascending order.
Var arr=; console.log (arr.sort ()); / / output: [1meme 3,4,5jue 9]
At this time, it is found that the data are arranged from small to large, no problem, so change the array to: var arr= [101meme1magentic 3magic5djinjin11]; and then call the sort () method to print the sorting results.
Var arr=; console.log (arr.sort ()); / / output: [1,101,11,3,4,5]
At this time, it is found that the array 101 sort 11 is ranked before 3 because the sort () method calls the array's toString () transformation method, and then compares the resulting strings to determine how to sort them, even if each item in the array is a numeric value, the sort () method compares strings.
So how are strings sorted? they are sorted from smallest to largest according to the unicode code of the string. Let's try to print out the unicode code for each item in the array.
/ / Transcoding method function getUnicode (charCode) {return charCode.charCodeAt (0) .toString (16);} / / print transcoding arr.forEach ((n) = > {console.log (String (n))}); / / output: 31 31 31 33 34 35 39
To my surprise, I found that the string unicode code of 1meme 101 ~ 11 is all 31.
2. Pass in the comparison function to specify the order
The above shows that the sort () method is not sorted in the order we want, so how to solve it? the sort () method can take a comparison function as an argument to specify which value precedes which value.
The comparison function (compare) takes two arguments, returns a negative number if the first parameter is before the second, 0 if the two parameters are equal, and an integer if the first parameter is after the second.
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, arrange the arr array, and print the result as follows:
Var arr=; console.log (arr.sort (compare)); / / output: [1meme 3,4,5jue 9,11,101]
You can find that there is nothing wrong with sorting from small to large.
3. Sort the array of objects
The sort () method sorts the array of numbers by passing in a comparison function, but in development, we sort a property of an array of objects, such as id, age, and so on.
To solve this problem, we can define a function, let it receive a property name, and then create a comparison function based on that property name and return it as a return value. (a function in JS can be used as a value, not only passing a function to another function as an argument, but also returning a function as a result of another function. Function as a first-class citizen in JS is not without reason, 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, and call the sort () method to pass in compareFunc (prop) to print the output:
Var users= [{name:'tom',age:18}, {name:'lucy',age:24}, {name:'jhon',age:17},]; console.log (users.sort (compareFunc ('age'); / / output result [{name: "jhon", age:17}, {name: "tom", age:18}, {name: "lucy", age:24}]
By default, when you call the sort () method without passing in the comparison function, the sort () method calls the toString () method of each object to determine their order, and when we call the compareFunc ('age') method to create a comparison function, the sort is sorted by the object's age property.
4. Sorting of XML nodes
Although many of the data returned by the background are in JSON format, it is very lightweight and easy to parse. But there was a project before because all the XML strings returned in the background have to be serialized after the front end gets the data, and some of them need to be sorted. The previous sorting is to convert XML into array objects for sorting, which is no problem. It just feels like the code is very redundant and troublesome. Later, on a whim, xml got a class array object, which can be sorted directly by converting the class array object into an array.
/ / 1. Simulate the XML string var str= `tom 18 lucy 24 jhon 17` / / 2 returned by the backend. Define the comparison function 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 strings are converted to xml objects var domParser = new DOMParser (); var xmlDoc = domParser.parseFromString (str, 'text/xml'); var userElements=xmlDoc.getElementsByTagName (' user'); / / 4.userElements class array objects are converted into arrays and then sort var userElements=Array.prototype.slice.call (xmlDoc.getElementsByTagName ('user')); var _ userElements=userElements.sort (compareFunction (' age')) / / 5. Print the sorted result _ userElements.forEach ((user) = > {console.log (user [XSS _ clean]);})
Print the sorted results
You can see that the XML nodes have been sorted by age from smallest to largest.
At this point, I believe you have a deeper understanding of "how to use sort in JavaScript". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.