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
8books.sort((a,b) => (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0));
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 list = [
2 { color: 'white', size: 'XXL' },
3 { color: 'red', size: 'XL' },
4 { color: 'black', size: 'M' }
5]
6
7var sortedArray = list.sort((a, b) => (a.color > b.color) ? 1 : -1)
8
9// Result:
10//sortedArray:
11//{ color: 'black', size: 'M' }
12//{ color: 'red', size: 'XL' }
13//{ color: 'white', size: 'XXL' }
1grossaryList = {
2 'bread': 1,
3 'apple': 6,
4 'milk': 1,
5 'orange': 3,
6 'broccoli': 2
7}
8
9return Object
10 .entries(grossaryList)
11 .sort((a,b) => b[1]-a[1])
12
13//=> [['apple', 6],['orange', 3],['broccoli', 2],['bread',1],['milk', 1]]
1function sortObjectByKeys(o) {
2 return Object.keys(o).sort().reduce((r, k) => (r[k] = o[k], r), {});
3}
4var unsorted = {"c":"crane","b":"boy","a":"ant"};
5var sorted=sortObjectByKeys(unsorted); //{a: "ant", b: "boy", c: "crane"}