Introduction
Below article will help you to understand basics of most used JavaScript methods which are map & filter.
.map(), .filter() & .reduce() all these are higher order functions & are part of JavaScript Array.Prototype method in JavaScript.
Array.Filter() Method
Syntax: array.filter(filterfunction())
As name suggests .filter() method filters the array on which it is called with the help of conditions present in filterfunction() which is given as argument to .filter() method.
const arr = [ 1, 9, 2, 8, 3, 7, 4, 6, 5];
const filterfunction = (element) => element > 5
const filteredArr = arr.filter(filterfunction);
// [ 9, 8, 7, 6 ]
const users = [
{
name: "Ram",
age: 21
},
{
name: "Sham",
age: 16
},
{
name: "Sita",
age: 15
},
{
name: "Gita",
age: 26
}
]
const adultUsers= users.filter((user)=> user.age > 18);
// [ {name: 'Ram', age: 21}, {name: 'Gita', age: 26} ]
As shown above filterfunction() is called for every element in array & as per conditions written in filterfunction() a new array with filtered elements is created.
Array.Map() Method
Syntax: array.map(mapfunction())
The map method is used to iterate over an array. In each iteration, it applies a mapfunction() function(callback) on every array element and finally returns a completely new array.
const arr = [ 2, 3, 4, 5, 6 ]
arr.map((item) => item*item )
// [4, 9, 16, 25, 36]
const users = [
{ firstName: 'Narendra', lastName: 'Modi', country: 'India' },
{ firstName: 'Joseph', lastName: 'Biden', country: 'USA' },
{ firstName: 'Vladimir', lastName: 'Putin', country: 'Russia' }
]
users.map((user) => user.firstName + " " + user.lastName )
// ['Narendra Modi', 'Joseph Biden', 'Vladimir Putin']
As shown above mapfunction() works as square calculator & returns square of number given to it. .map() calls the mapfunction() for every element in array & we get new array which has square of all the elements in old array.
End Note: Thank You for reading. If you have any suggestion or query please feel free to comment below. Good Day! Happy Coding!!!