0

Trying to filter through an array in Angular, and filter out all objects of a certain property

I have an array like this:

[  
   {  
      "group":"Group A",
   },
   {  
      "group":"Group A",
   },
   {  
      "group":"Group B",
   },
   {  
      "group":"Group B",
   } 
   {  
      "group":"Group C",
   },
   {  
      "group":"Group C",
   } 
]

...and I want to write a function to return an array with only Group A and B (not Group C).

So far this is what I have:

function filterStandings() {

        for (var i = 0, len = $scope.originalArray.length; i < len; i++) {
            $scope.filteredArr = [];
            if (originalArray[i].group !== "Group C") {
                 $scope.filteredStandingsArr.push($scope.originalArray[i]);
            }
         }
         return $scope.filteredArr;
 };

Then I when I try to display this array in my view by calling the filterStandings() function, nothing shows up.

Can anyone help?

1
  • You miss a "," in your example array, after the second { "group":"Group B", } Commented Jun 13, 2016 at 15:34

2 Answers 2

1

Array.prototype.filter()

For your use case:

 $scope.filteredArr = $scope.originalArray.filter(function(item){
    return item.group !== 'Group C'
 });
Sign up to request clarification or add additional context in comments.

Comments

0

Try this :

$scope.test = function () {
    $scope.filteredArr = [];
    for (var i = 0; i < $scope.items.length; i++) {
        if ($scope.items[i].group != "Group C") {
             $scope.filteredArr.push($scope.items[i]);
        }
     }
     return $scope.filteredArr;
 };

You have just miss to use the $scope services and initialize your new array (filteredArr) in the for-loop.

You can also use the filter keyword :

JS

$scope.filteredArr = function (item) {
       return item.group != "Group C";
};

HTML

<div ng:repeat="item in originalArray| filter: filteredArr ">
  {{item}}
</div>

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.