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);
1var names = ["Peter", "Emma", "Jack", "Mia", "Eric"];
2names.sort(); // ["Emma", "Eric", "Jack", "Mia", "Peter"]
3
4var objs = [
5 {name: "Peter", age: 35},
6 {name: "Emma", age: 21},
7 {name: "Jack", age: 53}
8];
9
10objs.sort(function(a, b) {
11 return a.age - b.age;
12}); // Sort by age (lowest first)
1var numArray = [140000, 104, 99];
2
3numArray.sort(function(a, b) {
4 return a - b;
5});
6
7// Array(3) [ 99, 104, 140000 ]
1var numArray = [140000, 32, 12, 63323, 104, 99];
2
3numArray.sort(function(a, b) {
4 return b - a;
5});
6
7// Array(6) [ 140000, 63323, 104, 99, 32, 12 ]