0

        
function sort(){

    var x=parseInt(document.getElementById("num1").value);
    var y=parseInt(document.getElementById("num2").value);
    var z=parseInt(document.getElementById("num3").value);


    if(x>y && x>z){

    if(y>z){
        alert(x+","+y+","+z);
    }
    else
    {
        alert(x+","+z+","+y)
    }

}

else if(y>x && y>z) {

    if(x>z){
        alert(y+","+x+","+z);
    }

    else{
        alert(y+","+z+","+x);
    }

}
else if(z>x && z>y){

        if(x>y){
            alert(z+","+x+","+y);
        }

        else{
            alert(z+","+y+","+x);
        }
    }
}
<input type="text" id="num1" name="">
    <input type="text" id="num2" name="">
    <input type="text" id="num3" name="">

    <button type="submit" onclick="sort()">Sort</button>

Hello Everyone, Can I ask there's another way to sort 3 numbers? Because the code is too long how to make it short or a better way to create this sort of numbers. Sorry Beginner here :).

woofMaranon
  • 144
  • 3
  • 15
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort – Marty Jun 26 '20 at 05:30
  • 3
    `[parseInt(document.getElementById("num1").value), parseInt(document.getElementById("num2").value), parseInt(document.getElementById("num3").value)].sort((a, b) => a - b)` [How to sort an array of integers correctly](https://stackoverflow.com/q/1063007) – VLAZ Jun 26 '20 at 05:31

2 Answers2

1

This array method will helps you.

var x = 20;
var y = 89;
var z = 61;

var arr = [];

arr.push(x);
arr.push(y);
arr.push(z);

console.log(arr.sort((a, b) => a - b)); 
sonEtLumiere
  • 4,461
  • 3
  • 8
  • 35
1

Just by using sort() you can do this easily.

function sort() {

  var sorting = []
  
  var x = parseInt(document.getElementById("num1").value);
  var y = parseInt(document.getElementById("num2").value);
  var z = parseInt(document.getElementById("num3").value);

  sorting.push(x, y, z)
  sorting.sort(function(a, b) {
   return a - b;
  });

  console.log(sorting)
}
<input type="text" id="num1" name="" required>
<input type="text" id="num2" name="" required>
<input type="text" id="num3" name="" required>

<button type="submit" onclick="sort()">Sort</button>
Always Helping
  • 14,316
  • 4
  • 13
  • 29
  • 2
    This is only correct for same digit numbers. Try it out with 1, 10 and 2. The default `.sort()` is alphanumeric/alphabetical. – Lain Jun 26 '20 at 05:37
  • @Lain Agree with you. MDN states this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort – Always Helping Jun 26 '20 at 05:41