Sorting Using JavaScript Array Sort() Method

The JavaScript sort() method – we will discuss about sort() method. How it work with string, numbers and character. Javascript sort method is used to sort the elements of an array and return new array.

Array sort method is used to sort JavaScript Array if manual code will be written to write the array, it will take a long time.

The javaScript Sort () function defines the value as strings. It works well for the strings. We will sort the array of element or items.

JavaScript Sort()

Contents

  • JavaScript sort() Syntax
  • Examples

JavaScript sort() Syntax

arr.sort([compareFunction])

Example of Numeric Sort

 var arr = [5, 3, 10, 1, 6, 12]
document.write("Array before sorting = " + arr);
document.write("<br>");
document.write("Array After sorting = " + arr.sort());
Output
//// return
Array before sorting = 5,3,10,1,6,12
Array After sorting = 1,10,12,3,5,6

Example 2 of Numeric sort

Sort an array ascending order using function.

var arr = [5, 3, 10, 1, 6, 12]
document.write("Array before sorting = " + arr);
document.write("<br>");
arr.sort(function(a, b) {
return a - b;
});
document.write("Array After sorting = " + arr);
Output
return //// Sort an array ascending order
Array before sorting = 5,3,10,1,6,12
Array After sorting = 1,3,5,6,10,12

Example 3 of Numeric sort

Sort an array descending order using function.

var arr = [5, 3, 10, 1, 6, 12]
document.write("Array before sorting = " + arr);
document.write("<br>");
arr.sort(function(a, b) {
return b - a;
});
document.write("Array After sorting = " + arr);
Output
return //// Sort an array descending order:

Array before sorting = 5,3,10,1,6,12
Array After sorting = 12,10,6,5,3,1

When the sort() function compares two values, so it will always return true or false. We pass the array in javascript sort function than it will proccess and check, return sorted array.

Example Of String Array Sort

 var arr = Array("php", "python", "javascript", "c", "c#", "rust");         
document.write("Array before sorting = " + arr);
document.write("<br>");
document.write("Array After sorting = " + arr.sort());
Output
return ///

Array before sorting = php,python,javascript,c,c#,rust
Array After sorting = c,c#,javascript,php,python,rust

Example 5

Extract a minimum value from an array.

 var arr = [5, 3, 10, 1, 6, 12]   
document.write("Array before sorting = " + arr);
document.write("<br>");
var result=arr.sort();
document.write("Minimum value of an array = " + arr[0]);
Output
//return

Array before sorting = 5,3,10,1,6,12
Minimum value of an array = 1

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *