Home  >  Article  >  Web Front-end  >  What is the function for sorting in javascript

What is the function for sorting in javascript

WBOY
WBOYOriginal
2021-12-23 10:56:483839browse

The sorting function in JavaScript is "sort()". The sort() function is used to sort the elements of the array. The sorted array elements can be letters or numbers. The sorting method can be ascending or descending order. The default sort order is alphabetical ascending, and the syntax is "array.sort(sortfunction)".

What is the function for sorting in javascript

The operating environment of this tutorial: Windows 10 system, JavaScript version 1.8.5, Dell G3 computer.

What is the sorting function in javascript

The sort() method is used to sort the elements of the array.

The sort order can be alphabetical or numerical, and in ascending or descending order.

The default sort order is ascending alphabetically.

Note: When the numbers are arranged in alphabetical order, "40" will be listed before "5".

To use numerical sorting, you must call it with a function as a parameter.

The function specifies whether the numbers are arranged in ascending or descending order.

These may be difficult to understand, but you can learn more about it through the examples at the bottom of this page.

Note: This method will change the original array! .

The syntax is as follows:

array.sort(sortfunction)

sortfunction is an optional parameter. Used to specify the sort order. Must be a function.

The example is as follows:

<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<p id="demo">单击按钮升序排列数组。</p>
<button onclick="myFunction()">点我</button>
<script>
function myFunction(){
var points = [40,100,1,5,25,10];
points.sort(function(a,b){return a-b});
var x=document.getElementById("demo");
x.innerHTML=points;
}
</script>
</body>
</html>

Output result:

What is the function for sorting in javascript

##[Related recommendations:

javascript learning tutorial

The above is the detailed content of What is the function for sorting in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn