Michael Michael - 7 months ago 8
Javascript Question

How to filter array of objects?

I have this array:

$scope.damageEvants =
[{"id":2, "StartDate":21/05/2012, EndDate:null},
{"id":3, "StartDate":null, EndDate:02/09/2014},
{"id":4, "StartDate":null, EndDate:null},
{"id":5, "StartDate":21/05/2012, EndDate:null}]


I want to filter(remove) all objects from array where property startDate and EndDate are null.

The result after filtering:

$scope.damageEvants =
[{"id":2, "StartDate":21/05/2012, EndDate:null},
{"id":3, "StartDate":null, EndDate:02/09/2014},
{"id":5, "StartDate":21/05/2012, EndDate:null}]


I tried this:

$scope.damageEvants.filter(return item.StartDate!== null && item.EndDate !== null )


But it seem to be wrong way.

How can filter
$scope.damageEvants
using filter function?

Answer
$scope.damageEvants.filter(return item.StartDate!== null && item.EndDate !== null )

supposed to be

$scope.damageEvants.filter(function(item) {
     return item.StartDate!== null && item.EndDate !== null;
});

Also the filter directive does not mutate the existing object. You would have to assign it to a variable to see the result.

   $scope.filtertedEvants =  $scope.damageEvants.filter(function(item) {
         return item.StartDate!== null && item.EndDate !== null;
    });
Comments