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

The method of sorting JavaScript arrays and numbers

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "the method of JavaScript array sorting and number sorting". In the daily operation, I believe that many people have doubts about the method of JavaScript array sorting and number sorting. Xiaobian consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts of "JavaScript array sorting and number sorting methods". Next, please follow the editor to study!

The sort () method is one of the most powerful array methods.

Array sorting

The sort () method sorts the array alphabetically:

Example

Var fruits = ["Banana", "Orange", "Apple", "Mango"]

Fruits.sort (); / / sort the elements in fruits

Reverse array

The reverse () method reverses the elements in the array.

You can use it to sort the array in descending order:

Example

Var fruits = ["Banana", "Orange", "Apple", "Mango"]

Fruits.sort (); / / sort the elements in fruits

Fruits.reverse (); / / reverses the element order

Numeric sorting

By default, the sort () function sorts values in string order.

This function works well with strings ("Apple" comes before "Banana").

However, if the numbers are sorted by string, "25" is greater than "100" because "2" is greater than "1".

For this reason, the sort () method produces incorrect results when sorting values.

We correct this problem with a ratio function:

Example

Var points = [40,100,1,5,25,10]

Points.sort (function (a, b) {return a-b})

Use the same technique to sort the array in descending order:

Example

Var points = [40,100,1,5,25,10]

Points.sort (function (a, b) {return b-a})

At this point, the study of "the method of sorting JavaScript arrays and numbers" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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

Development

Wechat

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

12
Report