I am using the function inputSetup
to prepare an array for a multi-select directive. I am passing in an array with the existing selections ($scope.item.categories
), an array with all the available categories, and a string the carries the context of the values "category".
Formatting the array to add the value "ticked" = true; on each object, so that the multi-select understand which options are selected.
Concatenating the arrays.
Sorting the arrays.
Using a for loop to iterate through the array and removing any duplicates that have the same "category" key... then removing the one that has "ticked" = false.
This code feels like it can be improved.
- Should the
.concat
and.sort
be chained together? - Should the for loop be replaced with an
array.filter()
?
$scope.categories = inputCategories($scope.item.categories, $scope.settings.categories, "category");
function inputSet (input, settings, category) {
var updatedSettings = [];
angular.forEach(input, function(obj) {
var setting = { "ticked": true };
setting[category] = obj;
updatedSettings.push(setting);
});
var list = updatedSettings.concat(settings);
list.sort(function(a, b) {
return (a[category] > b[category]) - (a[category] < b[category]);
});
for ( var i = 1; i < list.length; i++ ){
if(list[i-1][category] == list[i][category]) {
list.splice(i,1);
}
}
return list;
};