Skip to main content

JavaScript - Array sort

script.js

// get the html objects
const divText = document.getElementById("divText");


// function for button click
function sortArray(){
    // initialize an array of string values
    const colors = ["Canary", "Amber", "Blue", "Pink"];

    divText.innerHTML = "Array Elements";
    // for each loop through the array elements
    colors.forEach( item =>
            divText.innerHTML += "<br />" + item
    )


    // sort array elements in ascending order
    colors.sort();
    divText.innerHTML += "<br/><br/>Array Sorted (Ascending)";

    // for each loop through the array elements
    colors.forEach( item =>
            divText.innerHTML += "<br />" + item
    )

    
    // sort array elements in descending order
    // just revese the ascending sorted array elements
    colors.reverse();
    divText.innerHTML += "<br/><br/>Array Sorted (Descending)";

    // array sorted descending order
    colors.forEach( item =>
            divText.innerHTML += "<br />" + item
    )
}
index.html

<html>
  <head>
    <meta charset="UTF-8" />
    <script src="script.js" defer></script>
    <style>
      body{ 
        font-family:Arial, Helvetica, sans-serif;
        font-size: 25px; text-align: center;
      }
      button{
        padding: 20px; border-radius: 10px; outline: none;
        background-color: #FFAA1D; border: 2px solid #CD7F32;
      }
      div{padding: 20px;}
    </style>
  </head>

  <body>
    <div id="divContent">
      <h3>JavaScript : Array sort</h3>
      <button onclick="sortArray()">Sort Array</button>
      <div id="divText"></div>
    </div>
  </body>
</html>
More JavaScript tutorials