Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to add another function but different button in html javascript

I want to show arraylist in original order when i press the original order button and When i press the alphabetical i want to show the alphabetical order of the books i’ve only done the original order and I tried doing the same thing when adding the alp order but nothing happens
here’s the code

   <div id="result"></div>
   <button onclick="Org()">Original Order </button>
  
<script>
{
    var myArray=["Book1","Book2","Book3","Book4"]
     function Org(){
var display = myArray.toString();
document.getElementById("result").innerHTML = display;
}
}
  

  
  <button onclick="Alp()">Alphabetical Order</button>
  
  <button onclick="Rev()">Reverse Order</button>
  
</body>
</html>

i want to add a different function for Alphabetical order and Reverse order

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To sort array you can use sort() function. Check article.

Also, to keep original array, you can use it’s elements by using [...myArray] approach – in this case you will create new array, based on original array without changes.

To reverse array, use reverse() function.

// original array with strings
const myArray = ["Book1", "Book2", "Book3", "Book4"];

// getting result container
const resultContainer = document.querySelector("#result");

// printing original array
const Org = () => {
  const display = [...myArray].toString();
  resultContainer.innerHTML = display;
}

// printing sorted array
const Alp = () => {
  const display = [...myArray].sort().toString();
  resultContainer.innerHTML = display;
}

// printing reverted array
const Rev = () => {
  const display = [...myArray].sort().reverse().toString();
  resultContainer.innerHTML = display;
}
<div id="result"></div>
<button onclick="Org()">Original Order </button>
<button onclick="Alp()"> Alphabetical Order</button>
<button onclick="Rev()"> Reverse Order</button>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading