shady87 shady87 - 5 months ago 21
AngularJS Question

Add condition to AngularJS map function

I'm using the below to loop through an array and add a property to each item of the array.

$scope.addresses = $scope.addresses.map(function(address) {
address.location = "X";
return address;
});


this at the end will return all the items. How can I add a condition to the loop? so I can check a property and the based on that property return only certain addresses where that property is
true
?

Any help appreciated!

Answer

You should use the filter function

You can read about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

Basically filter is a function the gets a boolean function as a parameter (let's call it f), and returns an array with all the items that the f returns true for.

For example:

var mapped = $scope.addresses = $scope.addresses.map(function(address) {
      address.location = "X";   
      return address;
});

var filtered = mapped.filter(function (address) {
    return address.location.length > 5;
});

filtered will hold a collection of the addresses that have a location with more than 5 characters.