Skip to content Skip to sidebar Skip to footer

Angularjs How To Remove Duplicates By Multiple Select

a question to angular js. Let's say I have an array of objects eg: items = [ {'id':1,'name':'AAA'}, {'id':2,'name':'BBB'}, {'id':3,'name':'CCC'}, {'id':4,'name':'DDD'} ] Now I h

Solution 1:

You need to create a filter. Note: I am using the ES5 filter function, it won't work on IE8 unless your use a shim

yourModule.filter('exclude', function () {
    returnfunction (items, exclude) {
        return items.filter(function (item) {
            return exclude.indexOf(item.id) === -1;
        });
    });
});

And in your markup

<select type="text"class="form-control form-control-small" 
ng-model="itemId1" ng-options="item.id as item.name for item in items">
</select>

<select type="text"class="form-control form-control-small" 
ng-model="itemId2" ng-options="item.id as item.name for item in items | exclude:[itemId1]">
</select>

<select type="text"class="form-control form-control-small" 
ng-model="itemId3" ng-options="item.id as item.name for item in items | exclude:[itemId1, itemId2]">
</select>

If you want to update your selects if there is a change in the first or second one, use ngChange directive for resetting or changing other model values.

Solution 2:

Module.filter('exclude', function () {
    returnfunction (items, exclude) {
        return items.filter(function (item) {
            return exclude.indexOf(item.id) === -1; // Checking if the itemid is present already in the array
        });
    }
});

And in your markup

<select type="text"class="form-control form-control-small" 
ng-model="itemIdA" ng-options="item.id as item.name for item in items">
</select>

<select type="text"class="form-control form-control-small" 
ng-model="itemIdB" ng-options="item.id as item.name for item in items | exclude:[itemIdA]">
</select>

<select type="text"class="form-control form-control-small" 
ng-model="itemIdC" ng-options="item.id as item.name for item in items | exclude:[itemIdA, itemIdB]">
</select>

Solution 3:

I actually found a better (imho) solition. We just add a boolean field to the array, like:

{"id":1,"name":"AAA","show":true}

and filter to ng-options:

ng-options="item as item.name for item in items | filter : {"show : true}"

When selecting an item from the list we need to update to "show" value to false, so it won't be visible on the next select and update again to value true when when it is necessary. Anyway thx a lot for your help :)

Post a Comment for "Angularjs How To Remove Duplicates By Multiple Select"