How Map and Filter function works in RXJS

In order to understand how Map and Filter works , we can implement our own map function.
Map
Map in Rxjs used for projection, means you can transform the array in to entirely new array.

Array.prototype.map = function(projectionFunction){
var results=[];
this.forEach(function(item) {
results.push(projectionFunction(item));
});
return results;
};

You can see I have written a map function which accepts an anonymous function as a parameter. This will be your function to apply the projection to transform the array. Inside the map function you can see iterating each item in a array , call the project function by passing each item and finally the result of the projection function will push to the results array.

JSON.stringify([1,2,3].map(function(x){return x+1;}))

Output
[2,3,4]

https://www.learnrxjs.io/operators/transformation/map.html

Filter
Filter is used to filter an array based on some condition. You can specify the condition through an anonymous function. The implementation of Filter and Map are almost same only the difference is Map will transform each item in an array and will push to the main array. But the filter will only push to the main array if the condition pass.
var hotelCollection = [
{
"id": 9999,
"name": "Hotel XXX",
"place": "Wayne",
"rating": 5.0
},
{
"id": 8888,
"name": "Hotel YYY",
"place": "WoodCliff Lake",
"rating": 4.5
},
{
"id": 7777,
"name": "Hotel ZZZ",
"place": "Franklin Lake",
"rating": 5.0
},
{
"id": 6666,
"title": "Hotel PPP",
"place": "Lancester",
"rating": 4.3
},
];

Source

Array.prototype.filter=function(predicateFunction){
var results=[];
this.forEach(element => {
if(predicateFunction(element)){
results.push(element)
}
});
return results;
}

var collection = hotelCollection.filter(x=>x.rating===5);
https://www.learnrxjs.io/operators/filtering/filter.html
Thanks for reading

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s