5

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!

3 Answers 3

7

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);
Sign up to request clarification or add additional context in comments.

7 Comments

I can't try this, because I can't use in ES6.
@prog_prog your welcome, glad to help! (I am sorry for the es2015 syntax is just that I love it so much :P)
I like it too... maybe in the future... :-)
@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 ??
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 ;)
|
3

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.

2 Comments

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.)
But suppose you are using a key instead of string then just edit above like.. '!' + your_key
1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.