Hey Everyone .


Filter Function :
the basic use of this function is to get details of record from Array according to some properties. The filter function is very helpful with JSON Array.
Syntax : arrayname.filter((user define variable name)=>{return condition});Lets understand this with basic examples :
Q1. how to get all employees with gender male ?
var employee_list=[
{'id':'1','name':'Mukund Singh','gender':'M'},
{'id':'2','name':'Arun','gender':'M'},
{'id':'3','name':'Chanu','gender':'F'},
{'id':'4','name':'Main','gender':F'}
]
console.log(employee_list.filter((v)=>{return v.gender=='M'}));Here you will result :
[{'id':'1','name':'Mukund Singh','gender':'M'},
{'id':'2','name':'Arun','gender':'M'}]
Q2. how to get all products with active status true ?var product_list=[
{'id':'1','name':'Apple','is_active':true},
{'id':'2','name':'Pizza','is_active':false},
{'id':'3','name':'Milk','is_active':false},
{'id':'4','name':'Orange','is_active':true}
]console.log(product_list.filter((v)=>{return v.is_active}));Here you will result :[{'id':'1','name':'Apple','is_active':true},
{'id':'4','name':'Orange','is_active':true}]Q3. how to get all products with MRP more than 100 ?var product_list=[
{'id':'1','name':'Apple','mrp':20},
{'id':'2','name':'Pizza','mrp':1001},
{'id':'3','name':'Milk','mrp':200},
{'id':'4','name':'Orange','mrp':-40}
]console.log(product_list.filter((v)=>{return v.mrp>100}));Here you will result :[ {'id':'2','name':'Pizza','mrp':1001},{'id':'3','name':'Milk','mrp':200}]Q4. how to get all products with MRP more than 100 and active status true?var product_list=[
{'id':'1','name':'Apple','mrp':20,'is_active':true},
{'id':'2','name':'Pizza','mrp':1001,'is_active':true},{'id':'3','name':'Milk','mrp':200,'is_active':false},{'id':'4','name':'Orange','mrp':-40,'is_active':true}]console.log(product_list.filter((v)=>{return v.mrp>100 && v.is_active}));Here you will result :[ {'id':'2','name':'Pizza','mrp':1001,'is_active':true}]Q5. how to get all products with MRP more than 100 or active status true?var product_list=[
{'id':'1','name':'Apple','mrp':20,'is_active':false},
{'id':'2','name':'Pizza','mrp':1001,'is_active':true},{'id':'3','name':'Milk','mrp':200,'is_active':false},{'id':'4','name':'Orange','mrp':-40,'is_active':true}]console.log(product_list.filter((v)=>{return v.mrp>100 || v.is_active}));Here you will result :[ {'id':'2','name':'Pizza','mrp':1001,'is_active':true},{'id':'3','name':'Milk','mrp':200,'is_active':false},
{'id':'4','name':'Orange','mrp':-40,'is_active':true}]
Comments
Post a Comment