C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
JavaScript Array sort() methodThe JavaScript array sort() method is used to arrange the array elements in some order. By default, sort() method follows the ascending order. Syntax
The sort() method is represented by the following syntax: array.sort(compareFunction) Parameter
compareFunction - It is optional. It represents a function that provides an alternative sort order. Return
An array of sorted elements JavaScript Array sort() method exampleHere, we will understand sort() method through various examples. Example 1Let's see a simple example to sort the array of string elements. <script> var arr=["AngularJS","Node.js","JQuery","Bootstrap"] var result=arr.sort(); document.writeln(result); </script> Output: AngularJS,Bootstrap,JQuery,Node.js Example 2Let's see a simple example to sort the array of integer elements. <script> var arr=[2,4,1,8,5]; var result=arr.sort(); document.writeln(result); </script> Output: 1,2,4,5,8 Example 3Let's see an example to arrange the elements in ascending order using function.
<script>
var arr=[2,4,1,8,5];
var result=arr.sort(function compare(a,b)
{
return a-b;
});
document.writeln(result);
</script>
Output: 1,2,4,5,8 Example 4Let's see an example to arrange the elements in descending order using function.
<script>
var arr=[2,4,1,8,5];
var result=arr.sort(function compare(a,b)
{
return b-a;
});
document.writeln(result);
</script>
Output: 8,5,4,2,1 Example 5Let's see an example to extract minimum value from an array. <script> var arr=[2,4,1,8,5] var result=arr.sort(); //1,2,4,5,8 document.writeln(arr[0]); </script> Output: 1 Example 6Let's see an example to extract maximum value from an array. <script> var arr=[2,4,1,8,5] var result=arr.sort().reverse(); // 8,5,4,2,1 document.writeln(arr[0]); </script> Output: 8
Next TopicJavaScript Array
|