1homes.sort(
2 function(a, b) {
3 if (a.city === b.city) {
4 // Price is only important when cities are the same
5 return b.price - a.price;
6 }
7 return a.city > b.city ? 1 : -1;
8 });
1array.sort(function(a,b){
2 let i = 0, result = 0;
3 while(i < sortBy.length && result === 0) {
4 result = sortBy[i].direction*(a[ sortBy[i].prop ].toString() < b[ sortBy[i].prop ].toString() ? -1 : (a[ sortBy[i].prop ].toString() > b[ sortBy[i].prop ].toString() ? 1 : 0));
5 i++;
6 }
7 return result;
8})
9
1var sort_by;
2
3(function() {
4 // utility functions
5 var default_cmp = function(a, b) {
6 if (a == b) return 0;
7 return a < b ? -1 : 1;
8 },
9 getCmpFunc = function(primer, reverse) {
10 var dfc = default_cmp, // closer in scope
11 cmp = default_cmp;
12 if (primer) {
13 cmp = function(a, b) {
14 return dfc(primer(a), primer(b));
15 };
16 }
17 if (reverse) {
18 return function(a, b) {
19 return -1 * cmp(a, b);
20 };
21 }
22 return cmp;
23 };
24
25 // actual implementation
26 sort_by = function() {
27 var fields = [],
28 n_fields = arguments.length,
29 field, name, reverse, cmp;
30
31 // preprocess sorting options
32 for (var i = 0; i < n_fields; i++) {
33 field = arguments[i];
34 if (typeof field === 'string') {
35 name = field;
36 cmp = default_cmp;
37 }
38 else {
39 name = field.name;
40 cmp = getCmpFunc(field.primer, field.reverse);
41 }
42 fields.push({
43 name: name,
44 cmp: cmp
45 });
46 }
47
48 // final comparison function
49 return function(A, B) {
50 var a, b, name, result;
51 for (var i = 0; i < n_fields; i++) {
52 result = 0;
53 field = fields[i];
54 name = field.name;
55
56 result = field.cmp(A[name], B[name]);
57 if (result !== 0) break;
58 }
59 return result;
60 }
61 }
62}());
63