1function sortByKey(array, key) {
2 return array.sort((a, b) => {
3 let x = a[key];
4 let y = b[key];
5
6 return ((x < y) ? -1 : ((x > y) ? 1 : 0));
7 });
8}
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"}
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'}
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);
1/**
2 * Function to sort alphabetically an array of objects by some specific key.
3 *
4 * @param {String} property Key of the object to sort.
5 */
6function dynamicSort(property) {
7 var sortOrder = 1;
8
9 if(property[0] === "-") {
10 sortOrder = -1;
11 property = property.substr(1);
12 }
13
14 return function (a,b) {
15 if(sortOrder == -1){
16 return b[property].localeCompare(a[property]);
17 }else{
18 return a[property].localeCompare(b[property]);
19 }
20 }
21}