Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the sort method in JavaScript

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

Most people don't understand the knowledge points of this article "how to use the sort method in JavaScript", so Xiaobian summarizes the following contents for everyone. The contents are detailed, the steps are clear, and they have certain reference value. I hope everyone can gain something after reading this article. Let's take a look at this article "how to use the sort method in JavaScript".

1. Give me a chestnut

The array can be used directly to sort methods are: reverse() and sort(), because reverse() method is not flexible enough, there is a sort() method. By default, the sort() method sorts arrays in ascending order.

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

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

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

At this point, we find that arrays 101 and 11 are ranked before 3 because the sort() method calls the toString() transformation method of the array and then compares the resulting strings to determine how to sort them, even if each item in the array is a numeric value.

So how are strings sorted? They are sorted from small to large according to the unicode encoding of the string. Let's try printing 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(getUnicode(String(n)))});//output: 31 31 33 34 35 39

Surprisingly, the unicode code of the string 1, 101, 11 is 31.

2. Pass comparison function in specified order

The sort () method can take a comparison function as an argument to specify which value comes before which value.

The compare function takes two arguments and returns a negative number if the first argument precedes the second, 0 if the two arguments are equal, and an integer if the first argument follows 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, permute the arr array, and print the following:

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

You can see that sorting from small to large has no problem.

3. Sorting of object arrays

sort() method sorts an array of numbers by passing in a comparison function, but in development, we sort an array of objects for some attribute, such as id, age, etc., so how to solve it?

To solve this problem, we can define a function that accepts an attribute name, and then creates a comparison function based on that attribute name and returns it as a return value.(Functions in JS can be used as values, not only can one function be passed to another function like parameters, but also one function can be returned as the result of another function. Functions are first-class citizens in JS for a reason. They are really 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; } }}

定义一个数组users,调用sort()方法传入compareFunc(prop)打印输出结果:

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}]

在默认情况下,调用sort()方法不传入比较函数时,sort()方法会调用每个对象的toString()方法来确定他们的次序,当我们调用compareFunc('age')方法创建一个比较函数,排序是按照对象的age属性排序的。

4、XML节点的排序

尽管现在很多后台返回数据就是JSON格式的,很轻量又方便解析。但是之前有个项目因为后台返回的都是XML字符串,前端拿到数据后还得进行序列化,有些需要排序,之前的排序都是把XML转换成数组对象进行排序的,这样做没有什么问题,只不过感觉代码写的很冗余麻烦。后来就突发奇想,xml获取得到也是类数组对象,把类数组对象转换成数组不就可以直接排序了么。

// 1.模拟后端返回的XML字符串var str=` tom 18 lucy 24 jhon 17 ` // 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 string converted to xml object var domParser = new DOMParser();var xmlDoc = domParser.parseFromString(str, 'text/xml');var userElements=xmlDoc.getElementsByTagName ('user '));/ 4.userElements class array object converted to array reordering var userElements= Array.prototype.slice.call (xmlDoc.getElementsByTagName ('user'));var _userElements=userElements.sort(compareFunction ('age '));// 5. Print sorted results_userElements.forEach((user)=>{ console.log(user[xss_clean]);});

Print sorted results

You can see that the XML nodes are sorted by age from smallest to largest.

The above is about the content of this article on "how to use the sort method in JavaScript". I believe everyone has a certain understanding. I hope the content shared by Xiaobian will help everyone. If you want to know more relevant knowledge, please pay attention to the industry information channel.

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.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report