...

Web Technologies - JAVASCRIPT

Back to Course

Lesson Description


Lession - #219 Javascript Array Sort


The sort(>
method sorts the components of an array in place and returns the arranged or sorted array. The default sort order is ascending, based after changing over the components into strings, then, at that point, comparing their arrangements of UTF-16 code units values.

Syntax


// Functionless
sort(>
// Arrow function sort((firstEl, secondEl>
=> { /* ... */ } >
// Compare function sort(compareFn>
// Inline compare function sort(function compareFn(firstEl, secondEl>
{ /* ... */ }>

Let's see an example



<html>
   <head>
      <title>JavaScript Array sort Method</title>
   </head>
   
   <body>
      <script type = "text/javascript">
         var arr = new Array("orange", "mango", "banana", "sugar">
; var sorted = arr.sort(>
; document.write("Sorted string is : " + sorted >
; //Sorting numbers using sort method will sort using strings of the number var arr1 = new Array("25", "5", "2", "50">
; var sorted1 = arr1.sort(>
; document.write("

">
; document.write("Sorted numbers are : " + sorted1 >
; //Integers or numbers are sorted using campare function. var numArray = [25, 5, 2, 50]; numArray.sort(function(a, b>
{ return a - b; }>
; document.write("

">
; document.write(numArray>
; </script> </body> </html>

Output


Try it here