+ 1

How can I order 2 numbers from the lesser one to the greater one in JavaScript? Please help me to correct my try...

https://code.sololearn.com/W7w63ED8r6R0/?ref=app

21st Sep 2017, 5:52 PM
Sneider Aranda
Sneider Aranda - avatar
3 Antworten
+ 1
resultado = N1, N2; - this line of code will not work. var N1 = parseInt(prompt("Escriba un numero")); var N2 = parseInt(prompt("Escriba otro numero")); var higher; var lower; if (N1 > N2) { higher = N1; lower = N2; } else { higher = N2; lower = N1; } document.write("El orden ascendente es " + higher + ',' + lower); It's from higher to lower.If you want from lower to higher just change order inside document.write,like this. document.write("El orden ascendente es " + lower+ ',' + higher ); If you want to do this thing with more numbers then just 2 -> you need array.sort method and function which will sort.
21st Sep 2017, 11:38 PM
Rose Sevenyears
Rose  Sevenyears - avatar
+ 3
With Array.sort() you will reorder the array. Default ordering is done with string values (even if stored values are number), so ordering number is quite failing ^^ However, you can provide a callback function as argument of Array.sort() to perform sort as you want. The callback function expect two arguments: two items of your array to be compared: return -1 (or any negative value) if first is to be sorted first, 1 (or any positive) if second have to be, 0 if undeterminated... so working callback function to order numbers from lesser to greater will be: function mysort(a,b) { return b-a; } You can use it for sort() argument as named function, or even as anonymized one: arr.sort(mysort); or even arr.sort(function(a,b) { return b-a; }); Example: n = true; arr = []; while (n) { n = prompt('Enter a value?'); if (n) arr.push(n); } arr.sort(function(a,b) { return a-b; }); alert(''+arr);
22nd Sep 2017, 6:50 AM
visph
visph - avatar
0
how would that be for more numbers like you said... with array.sort ?
22nd Sep 2017, 3:47 AM
Sneider Aranda
Sneider Aranda - avatar