How to perform numeric sort in JavaScript?

HTMLJavascriptProgramming Scripts

To perform sorting in JavaScript, use the sort() function. You can try to run the following code sort numeric values.

Example

<!DOCTYPE html>
<html>
   <body>
      <script>
         var arr = [75, 20, 90, 9, 49, 32, 69, 66];
         document.write("Initial Values: "+arr);
         
         function myFunction() {
            arr.sort(function(val1, val2){return val1 - val2});
            document.write("<br>Sorted Values: "+arr);
         }
         myFunction();
      </script>
   </body>
</html>
raja
Published on 26-Feb-2018 09:50:03
Advertisements