-
Notifications
You must be signed in to change notification settings - Fork 0
/
groupBy.pipe.ts
45 lines (33 loc) · 1.04 KB
/
groupBy.pipe.ts
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
import { Pipe } from "angular2/core";
@Pipe({
name: "groupBy"
})
export class groupByPipe {
transform( collection: Object[] , term: string ) {
var newValue = [];
for (let i = 0; i < collection.length; i++) {
let keyVal = groupByPipe.deepFind(collection[i], term);
let index = newValue.findIndex( myObj => myObj.key == keyVal);
if (index >= 0) {
newValue[index].value.push(collection[i]);
} else {
newValue.push({key: keyVal, value: [collection[i]]});
}
}
return newValue;
}
static deepFind(obj, path) {
var paths = path.toString().split(/[\.\[\]]/);
var current = obj;
for (let i = 0; i < paths.length; ++i) {
if (paths[i] !== "") {
if (current[paths[i]] == undefined) {
return undefined;
} else {
current = current[paths[i]];
}
}
}
return current;
}
}