Filter NOT equals in AngularJS

22,099

Solution 1

Again, if you are just going to filter, use the native method instead:

$scope.array1 = data.filter(x => x.type === 1);
$scope.array2 = data.filter(x => x.type !== 1);

Solution 2

You're very close. You just need to change your second filter to:

$scope.array2 = $filter('filter')(data, { type: '!1' });

I also renamed the scope variable since otherwise it would just overwrite your first filtered array.

Solution 3

For me the given solution { type: '!1' } doesn't work when used with true as last parameter $filter('filter')(data, {type: 1}, true);. However using a function works for me (see angular's doc):

$scope.array2 = $filter('filter')(data, function(value, index, array) {
            return (value.type !== 1);
        }, true);
Share:
22,099
prog_prog
Author by

prog_prog

Updated on July 30, 2020

Comments

  • prog_prog
    prog_prog over 3 years

    I have a array of objects, in client side. The object in array look like this:

    {
        code: 0,
        short_name: 'a',
        type: 1
    }
    

    I try to filter this array to 2 arrays:

    1. With type === 1
    2. With type !== 1

    I did this:

    $scope.array1 = $filter('filter')(data, {type: 1}, true);
    $scope.array1 = $filter('filter')(data, {type: !1});
    

    But the not-equal didn't work... what can I do?

    Thank you!

  • prog_prog
    prog_prog about 8 years
    I tried it before but it's didn't work well... because this filter remove also all the object with type that include 1 (like: 12, 13, etc.)
  • prog_prog
    prog_prog about 8 years
    I can't try this, because I can't use in ES6.
  • Kutyel
    Kutyel about 8 years
    @prog_prog your welcome, glad to help! (I am sorry for the es2015 syntax is just that I love it so much :P)
  • prog_prog
    prog_prog about 8 years
    I like it too... maybe in the future... :-)
  • yogesh mhetre
    yogesh mhetre almost 7 years
    But suppose you are using a key instead of string then just edit above like.. '!' + your_key
  • chirag satapara
    chirag satapara almost 7 years
    @Kutyel , check this fiddle http://jsfiddle.net/U3pVM/33383/ , why last one is not display in list, event last one id is -12 not -1 ??
  • Kutyel
    Kutyel almost 7 years
    Hi @chiragsatapara, check the updated fiddle jsfiddle.net/U3pVM/33384, its a more practical example of how to use JS native functions instead of the angular "magic", which seems to be doing a string comparison or something like that (if this helped you please upvote the answer ;)
  • chirag satapara
    chirag satapara almost 7 years
    @Kutyel, for apply angular 'magic' , i have to make so much changes in my code , is there no way apply it in div using || filter : filters : true instead of js??
  • chirag satapara
    chirag satapara almost 7 years
    @Kutyel , if i change filter from ng-repeat , i have to make so much changes in my code , and it is not good for me.