I am creating an array sort number program where the user enters an array of numbers and clicking the Sort button will sort the numbers into numerical numbers. What I am wondering is how to get my program to ignore non-numbers? And how to set it to 1 number each line instead of putting them all on the same line?
var myarr = [];
function addTo() {
myarr.push(document.getElementById("userinput").value);
console.log(myarr); //to confirm it has been added to the array
};
function sortNumbers() {
myarr.sort(function(a, b){return a - b});
document.getElementById("userinput").append = myarr;
console.log(myarr);
}
<input type="number" id="userinput" />
<input type ="button" onclick="addTo()" value="Add Number" />
<button onclick="sortNumbers()">Sort</button>
Do you mean this?
var myarr = [];
function addTo() {
let n =document.getElementById("userinput").value;
myarr.push(n);
document.getElementById("inputA").innerText = myarr.toString();
};
function sortNumbers() {
myarr.sort(function(a, b) {return a - b});
;
let sortedB = document.getElementById("sortedB");
document.getElementById("sorted").innerText = myarr.toString();
sortedB.innerHTML = "";
myarr.forEach(n => sortedB.innerHTML += "<br/>" + n);
}
<input type="number" id="userinput" />
<input type ="button" onclick="addTo()" value="Add Number" />
<button onclick="sortNumbers()">Sort</button>
<p>Input array: <span id="inputA"></span></p>
<p>Sorted on one line: <span id="sorted"></span>
<br/>
Sorted on different lines: <span id="sortedB"></span>
</p>