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'}
1 function compareValues(key, order = 'asc') {
2 return function innerSort(a, b) {
3 if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) {
4 // property doesn't exist on either object
5 return 0;
6 }
7
8 const varA = (typeof a[key] === 'string')
9 ? a[key].toUpperCase() : a[key];
10 const varB = (typeof b[key] === 'string')
11 ? b[key].toUpperCase() : b[key];
12
13 let comparison = 0;
14 if (varA > varB) {
15 comparison = 1;
16 } else if (varA < varB) {
17 comparison = -1;
18 }
19 return (
20 (order === 'desc') ? (comparison * -1) : comparison
21 );
22 };
23}
1javascript sort object by value descending
2
3
4starWarsPeople.map(e=>{
5 return e
6 }).sort((a,b)=>{
7 if (a.height-b.height>1) {return -1;}
8 else if (a.height-b.height<1) {return 1;}
9 else {return 0;}
10 });
11