Skip to content Skip to sidebar Skip to footer

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:

Solution 1:

For decending order

sort should be

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

JSFIDDLE

Solution 2:

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]

Post a Comment for "Javascript Sorting Numbers"