Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Sorting Numbers

I am trying to sort the number in descending order using javascript. It works well for strings but when I use numbers it gives me wrong results.

Following is the code:

<html>
<head>
<script language ="Javascript">
function sort(form)
{
var a1=form.first.value
var b1 = form.second.value
var c1 =form.third.value
var a2= parseFloat(a1)
var b2=parseFloat(b1)
var c2= parseFloat(c1)
var rank_the_numbers = [a2,b2,c2]
rank_the_numbers.sort(function(a, b){return a-b})


document.writeln("The largest number is: "+rank_the_numbers[0])
document.writeln("<br> The second largest number is: " +rank_the_numbers[1])
 document.writeln("<br> The smallest number is: " +rank_the_numbers[2])
 document.writeln(rank_the_numbers)
}
</script>
</head>
<form onSubmit="return sort(this)">
Enter any three numbers: <br>
<input type="text" name="first" size=5><br>
<input type="text" name="second"size=5><br>
<input type="text" name="third" size=5><br>
<input type="submit" value= "Rank the numbers!" onClick = "sort(this.form)">
</form>
</body>
</html>

What changes should i make so that the code runs correctly for the numbers too. I went through a few articles on stackoverflow and used (function(a, b){return a-b}), but it too did not work.

like image 365
user5113176 Avatar asked Aug 05 '26 01:08

user5113176


1 Answers

For decending order

sort should be

rank_the_numbers.sort(function (a, b) {
    return b - a;
});

JSFIDDLE

like image 115
Anik Islam Abhi Avatar answered Aug 06 '26 16:08

Anik Islam Abhi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!