1// Sort an array of numbers
2let numbers = [5, 13, 1, 44, 32, 15, 500]
3
4// Lowest to highest
5let lowestToHighest = numbers.sort((a, b) => a - b);
6//Output: [1,5,13,15,32,44,500]
7
8//Highest to lowest
9let highestToLowest = numbers.sort((a, b) => b-a);
10//Output: [500,44,32,15,13,5,1]
11
1// Sort Numbers in Descending Order
2function sortDescending(num) {
3 return Number(num.toString().split('').sort((a, b) => b - a).join(''));
4//or: return parseInt(num.toString().split('').sort().reverse().join(''));
5}
6
7console.log(sortDescending(123)); // 321
8console.log(sortDescending(1254859723)); // 9875543221
1// ascending and discending for number
2const arr1 = [21, 2100, 2, 35000];
3const arr2 = [21, 2100, 2, 35000];
4
5let ascN = arr1.sort((f, s) => f - s);
6let dscN = arr2.sort((f, s) => s - f);
7
8// ascending and discending for string
9const arr3 = ['21', '2100', '2', '35000'];
10const arr4 = ['21', '2100', '2', '35000'];
11
12let ascS = arr3.sort((f, s) => f.length - s.length);
13let dscS = arr4.sort((f, s) => s.length - f.length);