1numArray.sort((a, b) => a - b); // For ascending sort
2numArray.sort((a, b) => b - a); // For descending sort
3
1var items = [
2 { name: 'Edward', value: 21 },
3 { name: 'Sharpe', value: 37 },
4 { name: 'And', value: 45 },
5 { name: 'The', value: -12 },
6 { name: 'Magnetic', value: 13 },
7 { name: 'Zeros', value: 37 }
8];
9
10// sort by value
11items.sort(function (a, b) {
12 return a.value - b.value;
13});
14
15// sort by name
16items.sort(function(a, b) {
17 var nameA = a.name.toUpperCase(); // ignore upper and lowercase
18 var nameB = b.name.toUpperCase(); // ignore upper and lowercase
19 if (nameA < nameB) {
20 return -1;
21 }
22 if (nameA > nameB) {
23 return 1;
24 }
25
26 // names must be equal
27 return 0;
28});
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)
1homes.sort(function(a, b) {
2 return parseFloat(a.price) - parseFloat(b.price);
3});