Created
September 29, 2015 19:45
-
-
Save wholypantalones/c6a0b055a5615eb4c416 to your computer and use it in GitHub Desktop.
Angular unique filter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.filter('unique', function () { | |
return function (items, filterOn) { | |
if (filterOn === false) { | |
return items; | |
} | |
if ((filterOn || angular.isUndefined(filterOn)) && angular.isArray(items)) { | |
var hashCheck = {}, newItems = []; | |
var extractValueToCompare = function (item) { | |
if (angular.isObject(item) && angular.isString(filterOn)) { | |
var resolveSearch = function(object, keyString){ | |
if(typeof object == 'undefined'){ | |
return object; | |
} | |
var values = keyString.split("."); | |
var firstValue = values[0]; | |
keyString = keyString.replace(firstValue + ".", ""); | |
if(values.length > 1){ | |
return resolveSearch(object[firstValue], keyString); | |
} else { | |
return object[firstValue]; | |
} | |
} | |
return resolveSearch(item, filterOn); | |
} else { | |
return item; | |
} | |
}; | |
angular.forEach(items, function (item) { | |
var valueToCheck, isDuplicate = false; | |
for (var i = 0; i < newItems.length; i++) { | |
if (angular.equals(extractValueToCompare(newItems[i]), extractValueToCompare(item))) { | |
isDuplicate = true; | |
break; | |
} | |
} | |
if (!isDuplicate) { | |
if(typeof item != 'undefined'){ | |
newItems.push(item); | |
} | |
} | |
}); | |
items = newItems; | |
} | |
return items; | |
}; | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment