How To Use .filter() In Angular

In this blog, you are going to see how to use .filter() function in Angular. I will explain to you how it works with a simple example.
 
You have an array containing multiple objects, each one representing an employee, but only want some of the objects in it. That’s where .filter() comes in.
 
Here is our data,
  1. var employees = [  
  2.   {  
  3.     "id": 11,  
  4.     "name""Ravishankar",  
  5.     "role""Developer"  
  6.   },  
  7.   {  
  8.     "id": 12,  
  9.     "name""Muthu",  
  10.     "role""Developer"  
  11.   },  
  12.   {  
  13.     "id": 13,  
  14.     "name""Mani",  
  15.     "role""Tester"  
  16.   },  
  17.   {  
  18.     "id": 14,  
  19.     "name""Ajith",  
  20.     "role""Tester"  
  21.   }  
  22. ]  
So we want two arrays, one for employee a role is a Developer and another one is for Tester. You can achieve this using .filter() like below,
  1. var developers = employees.filter(employee => employee.role == "Developer");  
  2.     
  3. var Testers = employees.filter(employee => employee.role == "Tester");   
If the callback function returns true then the current value will be stored in the array, if it returns false then it won't be.
 
That’s it, I hope you have learned how to use .filter() in Angular.