shady87 shady87 - 1 year ago 77
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 = $ {
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

Any help appreciated!

Answer Source

You should use the filter function

You can read about it here:

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 = $ {
      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.