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
>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>