The array.sort() is an inbuilt method in JavaScript which is used to sort the array. An array can be of any type i.e. string, numbers, characters etc.
Syntax:
array.sort()
Here array is the set of values which is going to be sorted.
Parameters: It does not accept any parameters.
Return values: It does not return anything.
Examples:
Input: var arr = ["Manish", "Rishabh", "Nitika", "Harshita"]; Output: Harshita, Manish, Nitika, Rishabh Input: var arr = [1, 4, 3, 2]; Output: 1, 2, 3, 4
Code #1: To sort an array of strings:
<html> <body> <p>Click on the Sort button to sort the array</p> <!-- button for click event --> <!-- onclick event is generated when the button is clicked --> <p id= "demo" ></p> <script> <!-- array of names --> var names = [ " Manish" , " Rishabh" , " Nitika" , " Harshita" ]; document.getElementById( "demo" ).innerHTML = names; <!-- sortAlphabet function that sort above array alphabetically --> function sortAlphabet() { names.sort(); document.getElementById( "demo" ).innerHTML = names; } </script> <button onclick= "sortAlphabet()" > Sort </button> </body> </html> |
Output:
Before clicking the “sort” button-
After clicking the “sort” button-
Code #2: To sort an array of integers:
<html> <body> <p>Click on the Sort button to sort the array</p> <!-- button for click event --> <!-- onclick event is generated when the button is clicked--> <p id= "demo" ></p> <script> <!-- array numbers --> var numbers = [7, 1, 6, 9, 2]; document.getElementById( "demo" ).innerHTML = numbers; <!-- sortNumber function that sort the array --> function sortNumber() { numbers.sort(); document.getElementById( "demo" ).innerHTML = numbers; } </script> <button onclick= "sortNumber()" > Sort </button> </body> </html> |
Output:
Before clicking the “sort” button-
After clicking the “sort” button-
This article is attributed to GeeksforGeeks.org
0
0
leave a comment
0 Comments