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*/
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
1const books = [
2 {id: 1, name: 'The Lord of the Rings'},
3 {id: 2, name: 'A Tale of Two Cities'},
4 {id: 3, name: 'Don Quixote'},
5 {id: 4, name: 'The Hobbit'}
6]
7
8compareObjects(object1, object2, key) {
9 const obj1 = object1[key].toUpperCase()
10 const obj2 = object2[key].toUpperCase()
11
12 if (obj1 < obj2) {
13 return -1
14 }
15 if (obj1 > obj2) {
16 return 1
17 }
18 return 0
19}
20
21books.sort((book1, book2) => {
22 return compareObjects(book1, book2, 'name')
23})
24
25// Result:
26// {id: 2, name: 'A Tale of Two Cities'}
27// {id: 3, name: 'Don Quixote'}
28// {id: 4, name: 'The Hobbit'}
29// {id: 1, name: 'The Lord of the Rings'}
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
1let orders = [
2 {
3 order: 'order 1', date: '2020/04/01_11:09:05'
4 },
5 {
6 order: 'order 2', date: '2020/04/01_10:29:35'
7 },
8 {
9 order: 'order 3', date: '2020/04/01_10:28:44'
10 }
11];
12
13
14console.log(orders);
15
16orders.sort(function(a, b){
17 let dateA = a.date.toLowerCase();
18 let dateB = b.date.toLowerCase();
19 if (dateA < dateB)
20 {
21 return -1;
22 }
23 else if (dateA > dateB)
24 {
25 return 1;
26 }
27 return 0;
28});
29
30console.log(orders);