settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Sort numbers in ascending order and descending order in JavaScript

+4 votes
How to sort numbers in ascending order (from the smallest to the largest number. E.g. 5, 9, 13) and descending order (from the largest to the smallest number. E.g. 13, 9, 5) in JavaScript?
asked in JavaScript category by user Jolie Ann

2 Answers

+3 votes

The code below is for the ascending order:

function sortNums(arr) {
    let sorted = arr.sort((a, b) => a - b);
    console.log(sorted.join(", "));
}

sortNums([4, 15, -1, 0]);

... and this is for the descending order:

function sortNums(arr) {
    let sorted = arr.sort((a, b) => b - a);
    console.log(sorted.join(", "));
}

sortNums([4, 15, -1, 0]);

with lambda function. See how to use arrow (lambda) functions here

answered by user ak47seo
+1 vote
answered by user hues
edited by user golearnweb
...