Sort Number, Decimal, String, Dates and time in JavaScript

How to Sort numbers, Decimal numbers, String, Date, and Time using Javascript. In this Javascript tutorial, let us see How we will perform the following operation on numbers, String, Date, and Times.

How to sort numbers using Javascript?

Problem Statement

How to sort three numbers using conditional statements and display results in an alert box. For that create an HTML file and return the result using the jS function.

Solution

  • Create Html file
  • Use numbers
  • Use JS functions
  • Display result on the output screen

JS code to display sort numbers in JS

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>

<p>JavaScript conditional statement to sort three numbers. Display an alert box to show the result. <br/> 
Sample numbers : 1, -1, 4 <br/> 
Output : 4, 1, -1
</p><br/> 

<div><strong>Result</strong></div>
<input type="text" name="" id="input" value="[1, -1, 4]" disabled><button id="submit">ок</button>
<div id="result"></div>
</head>
<body>
    <script>
         (function() {
    document.getElementById('submit').addEventListener('click',init);
    document.getElementById('input').addEventListener('focus', function() { this.value = "" });
    function init() {
        var elem = document.getElementById('input'),
            elemValue = elem.value.split(","),
            sampleArr = [1, -1, 4];
        elem.value = sortAny(sampleArr);
    }
    function sortAny(arr) {
        var temp,
            swap = true;
        while (swap == true) {
             swap = false;
             for (var i = 0; i < arr.length; i++) {
                 if (arr[i] < arr[i+1]) {
                     temp = arr[i];
                     arr[i] = arr[i+1];
                     arr[i+1] = temp;
                     swap = true;
                 }
             }
        }
        alert(arr);
        return '['+arr+']';
    }
    
     function sortThree(n,nTwo,nThree) {
         var arr = [n,nTwo,nThree],
             largest,
             secondLargest,
             smallest,
             lI,
             sI;
         n > nTwo ? largest = n : largest = nTwo;
         largest > nThree ? secondLargest = nThree : secondLargest = largest, largest = nThree;
         lI = arr.indexOf(largest), sI = arr.indexOf(secondLargest);
         arr.splice(lI,1), arr.splice(sI,1);
         smallest = arr[0];
         arr.length = 0;
         arr.push(largest), arr.push(secondLargest), arr.push(smallest);
         alert(arr);
         return '['+arr+']'
     }
})();
    </script>
</body>
</html>

Output

In this way, we learned how to sort numbers display in the alert box in js.

How to sort string data in JavaScript?

Problem statement

In this, you have to sort data of string in javascript using the JS functions for that you have to create Html file and JS function returns the result on output screen so run that Html file.

Solution

  • Create Html file
  • Create an array of data
  • Use function document.write(“Original String</br>”)
  • Then for printing document.write(string)
  • Run HTML file

JS code  to sort string data in JavaScript

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Sort string data using js</title>
</head>
<body>
<script>
var string = ["Suraj", "Sanjeev", "Rajnish", "Yash", "Ravi"];
      
// Print original string array
document.write("Original String</br>");
document.write(string);
      
document.write("</br>");
      
// Use sort() method to sort the strings
string.sort();
      
document.write("</br>After sorting</br>");
      
// Print sorted string array
document.write(string);
      
</script>
</body>
</html>

Output

How to sort decimal data in JavaScript?

Problem statement

In this, you have to sort decimal data Using the javascript function for that you have to create an HTML file and function return results using the console function.

Solution

  • Create Html file as xyz.html
  • Create an array of numbers
  • Use function const compare = (a, b)
  • Use if loop for the sorting
  • Display result in console for that runs Html file to sort decimal data in JavaScript

JS code to sort decimal data in JavaScript

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Sorting decimal data array of string</title>
</head>
<body>
    <script>
        const arr = [ '.0', '.1', '.2', '.4', '.2.1', '.3', '.4.1', '.5', '.5.1.5' ];
const compare = (a, b) => {
   if (a === b) {
      return 0
   };
   const aArr = a.split("."), bArr = b.split(".");
   for (let i = 0; i < Math.min(aArr.length, bArr.length); i++) {
      if (parseInt(aArr[i]) < parseInt(bArr[i])) {
         return -1
      };
      if (parseInt(aArr[i]) > parseInt(bArr[i])) {
         return 1
      };
   }
   if (aArr.length < bArr.length) {
      return -1
   };
   if (aArr.length > bArr.length) {
      return 1
   };
   return 0;
};
arr.sort(compare);
console.log(arr);
    </script>
</body>
</html>

Output

How to sort Dates and Time in JavaScript?

Problem statement

In this, you have to sort dates and time in javascript using functions that create Html file and the JS function return the result on the output screen.

Solution

  • Create Html file  as .html
  • Create array
  • Use array.sort(function (a, b) 
  • Run html file

JS code to sort Dates and time in JavaScript

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Sorting date and time in JS</title>
</head>
<body>
    <script>
        array = [{
  			id: 1, name: "test1", date: "2020-01-05",
            id: 2, name: "test2", date: "2020-01-02"
        }]

array.sort(function (a, b) {
    var dateA = new Date(a.date), dateB = new Date(b.date)
    return dateA - dateB
});

console.log(array) ;
    </script>
</body>
</html>

Output

Thus, in this way, we learned How to Sort numbers, Decimal numbers, String, Date, and Time using Javascript.