1let list = [
2 {
3 name: "world"
4 },
5 {
6 name: "hello",
7 },
8];
9
10// This doesn't account for if names are the same between objects
11let x = list.sort((a, b) => (a.name > b.name ? 1 : -1));
12
13console.log(x);
14
15/*
16[
17 {
18 name: "hello",
19 },
20 {
21 name: "world"
22 },
23];
24*/
1function compareFirstNames( a, b ) {
2 if ( a.first_name < b.first_name ){
3 return -1;
4 }
5 if ( a.first_name > b.first_name ){
6 return 1;
7 }
8 return 0;
9}
10
11var people =[
12 {"first_name":"Carol", "age":29},
13 {"first_name":"Anna", "age":32},
14 {"first_name":"Bob", "age":32}
15];
16
17people.sort( compareFirstNames ); //people is now sorted by first name from a-z
1function sortByDate( a, b ) {
2 if ( a.created_at < b.created_at ){
3 return -1;
4 }
5 if ( a.created_at > b.created_at ){
6 return 1;
7 }
8 return 0;
9}
10
11myDates.sort(sortByDate);//myDates is not sorted.
1var maxSpeed = {
2 car: 300,
3 bike: 60,
4 motorbike: 200,
5 airplane: 1000,
6 helicopter: 400,
7 rocket: 28800
8};
9var sortable = [];
10for (var vehicle in maxSpeed) {
11 sortable.push([vehicle, maxSpeed[vehicle]]);
12}
13
14sortable.sort(function(a, b) {
15 return a[1] - b[1];
16});
17
18//[["bike", 60], ["motorbike", 200], ["car", 300],
19//["helicopter", 400], ["airplane", 1000], ["rocket", 28800]]