0

I have a scope variable that looks as follows:

 $scope.people = [
      {'id':'1' ,'name':'John','category':'m'},
      {'id':'2', 'name':'Jack','category':'m'},
      {'id':'3','name':'Mark','category':'m'},
      {'id':'4','name':'Ernie','category':'m'},
      {'id':'5','name':'Jane','category':'w'},
      {'id':'6','name':'Jill','category':'w'},
      {'id':'7','name':'Betty','category':'w'},
      {'id':'8','name':'Mary','category':'w'}
      ];

This is a sample scope variable i created for the puspose of this problem. But i will be getting this data from a service. What i would like to achieve is, how do i filter this scope variable in to different variables from within the controller?

For example, i want to make 2 new scopes as follows from the given scope:

$scope.men = [
          {'id':'1' ,'name':'John','category':'m'},
          {'id':'2', 'name':'Jack','category':'m'},
          {'id':'3','name':'Mark','category':'m'},
          {'id':'4','name':'Ernie','category':'m'}
          ];

$scope.women = [
          {'id':'5','name':'Jane','category':'w'},
          {'id':'6','name':'Jill','category':'w'},
          {'id':'7','name':'Betty','category':'w'},
          {'id':'8','name':'Mary','category':'w'}
          ];

How do i achieve this? Any knowledge will be very helpful

0

2 Answers 2

1

You could use array.filter:

function isMan(person){
    return person.category == 'm';
}

function isWoman(person){
    return person.category == 'w';
}

$scope.men = $scope.people.filter(isMan);
$scope.women = $scope.people.filter(isWoman);

Fiddle

For older browsers you would need to polyfill filter.

Alternatively you could user underscore's filter function.

Sign up to request clarification or add additional context in comments.

2 Comments

hi...it worked great. can you tell me if there is a similar way to join 2 scope variables?
The scope properties are just javascript types so you can use concat to concatenate arrays.
0

You need to use some javascript lib like underscore.js

As an example

  _.groupBy($scope.people, function(v){ return v.category == 'm' });

Not sure about source code.

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.