1var array = [
2 {name: "John", age: 34},
3 {name: "Peter", age: 54},
4 {name: "Jake", age: 25}
5];
6
7array.sort(function(a, b) {
8 return a.age - b.age;
9}); // Sort youngest first
1var items = ['réservé', 'premier', 'communiqué', 'café', 'adieu', 'éclair'];
2items.sort(function (a, b) {
3 return a.localeCompare(b); //using String.prototype.localCompare()
4});
5
6// items is ['adieu', 'café', 'communiqué', 'éclair', 'premier', 'réservé']
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
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)
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})
24
1you can sort array in different ways:
2
3first....by using the sort method
4ex: let arr = ["a", "d", "b", "c", "f"]
5let res = arr.sort()
6NOTE: this method is not ideal
7
8
9second...... by using the sort function
10ex: let arr = [1, 10, 11, 30, 100, 50, 45]
11
12let res = arr.sort((a, b)=> a - b ).....this sorts in ascending order
13let res = arr.sort((a, b)=> b - a ) ...this sorts in descending order
14
15NOTE: we can also user different algorithms to sort an array. example: bubble sort,
16 quick sort, merge sort etc.
17
18 answer by EZIOGOR CLEVER