I'm trying to sort numbers in ascending or descending order, depending on the user input. I sorted the numbers in the text fields into an array and using an if-else statement to sort in ascending or descending order depending on the value of the select tag. However, the code only sorts in ascending order and does not sort in descending order when told to. I'm just wondering what I can do to fix this.
This is my first coding in HTML and Javascript, let alone coding at all so this code is probably very inefficient, but I'm willing to accept any tips.
function sortingFunction() {
var arr = [];
arr.push(document.getElementById("one").value);
arr.push(document.getElementById("two").value);
arr.push(document.getElementById("three").value);
arr.push(document.getElementById("four").value);
arr.push(document.getElementById("five").value);
arr.push(document.getElementById("six").value);
arr.push(document.getElementById("seven").value);
arr.push(document.getElementById("eight").value);
arr.push(document.getElementById("nine").value);
arr.push(document.getElementById("ten").value);
var filtered = arr.filter(Boolean);
var x = document.getElementById("mySelect").value;
if (x = "ascending") {
document.getElementById("answer").innerHTML = "Answer: " + filtered.sort(function(a,b) { return a - b;});
} else {
document.getElementById("answer").innerHTML = "Answer: " + filtered.sort(function(a,b) { return b - a;});
}
}
//Text Fields Here with id="one" to "ten"
<button onclick="sortingFunction()">Submit</button>
<select name="test" id="mySelect">
<option value="ascending">Ascending Order</option>
<option value="descending">Descending Order</option>
</select>
<p id="answer"></p>