0

For filtering a javascript array using angular filter the syntax is

$filter('filter')(array, expression, comparator, anyPropertyKey)

As per angular documentation the second parameter expression can take

A pattern object to filter specific properties on objects contained by array. For example {name:"M", phone:"1"} predicate will return an array of items which have property name containing "M" and property phone containing "1"

in the mentioned example we are getting condition as name matching "M" and phone matching "1"

but how to achieve condition as name matching "M" or phone matching "1"

code sample

var employees=[
  {lastname:"john",firstname:"jack",age:40,sex:"m"},
  {lastname:"Abby",firstname:"john",age:20,sex:"f"},
  ];

var filteredData =$filter('filter')(employees,{firstname:'john', lastname:'john'});

this results up with no records since and is applied can we try to filter records having lastname or first name as 'john'

is this possible to achieve with out using custom filters

lrvkiran
  • 3
  • 4

1 Answers1

0

var myApp = angular.module('myApp', []);

myApp.controller('myCtrl', ['$scope', '$filter', function($scope, $filter){

  var employees=[
  {lastname:"john",firstname:"jack",age:40,sex:"m"},
  {lastname:"Abby",firstname:"john",age:20,sex:"f"},
  {lastname:"Abby",firstname:"mark",age:20,sex:"f"},
  ];
  
$scope.filteredData = $filter('filter')(employees, function(value){
        return value.firstname == 'john' || value.lastname == 'john';
});

console.log($scope.filteredData);
 
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!DOCTYPE html>
<html ng-app="myApp">

<body>

  <div ng-controller="myCtrl">
    {{filteredData}}
  </div>


</body>

</html>

you can use like below.

$scope.filteredData = $filter('filter')(employees, function(value){
        return value.firstname == 'john' || value.lastname == 'john';
});
Ketan Modi
  • 1,780
  • 1
  • 16
  • 28