- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultiFieldSortingACollection.js
More file actions
Latest commit
54 lines (48 loc) · 1.99 KB
/
Copy pathMultiFieldSortingACollection.js
File metadata and controls
54 lines (48 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Example of sorting the elements of a collection using multiple sort keys.
vardata=[{
fieldA: 'E',
fieldB: 'D'
},{
fieldA: 'A',
fieldB: 'Z1C'
},{
fieldA: 'AA',
fieldB: 'C1C'
},{
fieldA: 'B2',
fieldB: 'A2C'
},{
fieldA: 'C3A',
fieldB: 'C3AA'
}];
// -----------------------------------------------------------------------------------------
// Good Approch - Apply a stable sort for each field in reverse order.
// -----------------------------------------------------------------------------------------
vartoSort=_.chain(data);
sortFields.reverse().forEach(function(x){toSort=toSort.sortBy(x);});
varsorted=toSort
.map(function(x){returnx.fieldA+', '+x.fieldB;})
.value();
console.log("Correct Sort",sorted);
// Correct Sort ["A, Z1C", "AA, C1C", "B2, A2C", "C3A, C3AA", "E, D"]
// -----------------------------------------------------------------------------------------
// Bad Approch - Concatinate the sort fields together into a composite key. This doesn't take
// field length into account when sorting so you end up comparing sections of different fields.
// -----------------------------------------------------------------------------------------
varsortFields=['fieldA','fieldB'];
data.forEach(function(x){
varsortKey=_.reduce(sortFields,function(memo,field){returnmemo+x[field];},'');
console.log("Composite key: ",sortKey);
});
// Composite key: AZ1C <- See how the 'Z' of data[0]'s fieldB is compared against data[1]'s 'A' of fieldA
// Composite key: AAC1C
varbadSorted=_.chain(data)
.sortBy(function(x){
// Build a composite key to use for sorting by concatinating the sort fields
return_.reduce(sortFields,function(memo,field){returnmemo+x[field];},'');
})
.map(function(x){returnx.fieldA+','+x.fieldB;})
.value();
console.log("Incorrect Sort",badSorted);
// Incorrect Sort ["AA,C1C", "A,Z1C", "B2,A2C", "C3A,C3AA", "E,D"]
// "A,Z1C" should have been first!!!