3

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.

2 Answers 2

2

For decending order

sort should be

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

JSFIDDLE

Sign up to request clarification or add additional context in comments.

Comments

0

Javascript inbuilt sort function sorts alphabetically

const numbers = [1,12,5,13,2,15,4,11,3,10];

so sorting numbers directly would return alphabetically sorted array

const sortedAlphabet = numbers.sort();
// Output: [1, 10, 11, 12, 13, 15, 2, 3, 4, 5]

while if you want to sort numbers in ascending order this is the way to do it

const sortedNumbers = numbers.sort((a, b) => a-b);
// Output: [1, 2, 3, 4, 5, 10, 11, 12, 13, 15]

and if you want to sort numbers in descending order this is the way to do it

const sortedNumbers = numbers.sort((a, b) => b-a);
// Output: [15, 13, 12, 11, 10, 5, 4, 3, 2, 1]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.