Skip to content
This repository was archived by the owner on Jan 24, 2019. It is now read-only.

Commit 154722c

Browse files
committed
Merge pull request #28 from aidanhs/unique-filter-object-subkeys
Fix unique filter on object subkeys
2 parents 9fc207f + c8c298d commit 154722c

File tree

2 files changed

+17
-8
lines changed

2 files changed

+17
-8
lines changed

modules/unique/test/uniqueSpec.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,18 @@ describe('unique', function () {
5454
]);
5555
});
5656

57+
it('should return unique entries based on the subkey provided for complex objects', function () {
58+
var arrayToFilter = [
59+
{key: 'value', other: {subkey: 'sub1'}},
60+
{key: 'value', other: {subkey: 'sub2'}},
61+
{key: 'value2', other: {subkey: 'sub1'}}
62+
];
63+
expect(uniqueFilter(arrayToFilter, 'other.subkey')).toEqual([
64+
{key: 'value', other: {subkey: 'sub1'}},
65+
{key: 'value', other: {subkey: 'sub2'}}
66+
]);
67+
});
68+
5769
it('should return unique primitives in arrays', function () {
5870
expect(uniqueFilter([1, 2, 1, 3])).toEqual([1, 2, 3]);
5971
});

modules/unique/unique.js

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
if the key === false then no filtering will be performed
66
* @return {array}
77
*/
8-
angular.module('ui.unique',[]).filter('unique', function () {
8+
angular.module('ui.unique',[]).filter('unique', ['$parse', function ($parse) {
99

1010
return function (items, filterOn) {
1111

@@ -14,14 +14,11 @@ angular.module('ui.unique',[]).filter('unique', function () {
1414
}
1515

1616
if ((filterOn || angular.isUndefined(filterOn)) && angular.isArray(items)) {
17-
var hashCheck = {}, newItems = [];
17+
var hashCheck = {}, newItems = [],
18+
get = angular.isString(filterOn) ? $parse(filterOn) : function (item) { return item; };
1819

1920
var extractValueToCompare = function (item) {
20-
if (angular.isObject(item) && angular.isString(filterOn)) {
21-
return item[filterOn];
22-
} else {
23-
return item;
24-
}
21+
return angular.isObject(item) ? get(item) : item;
2522
};
2623

2724
angular.forEach(items, function (item) {
@@ -42,4 +39,4 @@ angular.module('ui.unique',[]).filter('unique', function () {
4239
}
4340
return items;
4441
};
45-
});
42+
}]);

0 commit comments

Comments
 (0)