Removing element from array invalidates iterator

In AngularJS, I am trying to remove every category that has a count of 0 from the categories array.

// remove all categories that have a count of 0
i = 0;
angular.forEach( $scope.categories, function( category )
{           
    if( category.count == 0)
    {
        $scope.categories.splice( i, 1 );
    }
    i++;
});

This code removes the first category with 0 count from the array, but not the next one. I suppose, splice invalidates the iterator? How can I fix the problem?

You could use filter method available on Array objects of javascript version 1.6 or greater.

function countFilter(category, index, array) {
  return (category.count != 0);
}
$scope.categories = $scope.categories.filter(countFilter);

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter

If you need to support older versions of javascript checkout the compatibility section of the link above.

I would just create a new array that has non-zero counts. Something like this:

// remove all categories that have a count of 0
var nonZeroCategories = [];
angular.forEach( $scope.categories, function( category )
{           
    if( category.count > 0)
    {
        nonZeroCategories.push(category)
    }
});
$scope.categories = nonZeroCategories;

Also, as an FYI, the iterator function has a 2nd parameter that is the index, so in case you ever need it, you don't need to declare an i outside the forEach. You can just do:

angular.forEach( $scope.categories, function( category, i ) {
    .....