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
1numArray.sort((a, b) => a - b); // For ascending sort
2numArray.sort((a, b) => b - a); // For descending sort
3
1const points = [40, 100, 1, 5, 25, 10];
2points.sort(function(a, b){return a - b}); // for ascending
3//another way for ascending
4points.sort((a,b)=>{
5 if(a>b){
6 return 1
7 }else if(a<b){
8 return -1
9 }else{
10 return 0
11 }
12})
13points.sort(function(a, b){return b - a}); // for descending
14//another way for descending
15points.sort((a,b)=>{
16 if(a>b){
17 return -1
18 }else if(a<b){
19 return 1
20 }else{
21 return 0
22 }
23})
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)
1let numbers = [4, 10, 5, 1, 3];
2numbers.sort((a, b) => a - b);
3console.log(numbers);
4
5// [1, 2, 3, 4, 5]