1numArray.sort((a, b) => a - b); // For ascending sort
2numArray.sort((a, b) => b - a); // For descending sort
3
1 strData = ["banana", "apple", "zebra", "jos"];
2 numData = [1, 3, 2, 5, 6];
3 objData = [
4 { name: 'Alex', age: 20 },
5 { name: 'Karlsson', age: 19 },
6 { name: 'Noah', age: 21 },
7 ];
8
9
10 // sort str alfabeticly (a-z)
11 strData.sort((a,b) => {
12 return a === b ? 0 : a < b ? -1 : 1
13 });
14 console.log(strData)
15
16
17 // sort Objdata uppifrån å ner (ålder 19-21)
18 objData.sort((a,b) => a.age - b.age)
19 console.log(objData);
20
21
22 // Small number to large number
23 numData.sort()
24 console.log(numData);
25 // Large number to small number
26 numData.sort((a,b) => b-a)
27 console.log(numData);
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)
1// sort an array
2// by drinks: lowest to highest
3function sortDrinkByPrice(drinks) {
4 return drinks.sort((a, b) => {
5 return a.price - b.price;
6 });
7}
8
9// parse the array as parameters within the function
10console.log(sortDrinkByPrice([{name: "lemonade", price: 50},{name: "lime", price: 10}]));