How to use map and filter simultaneously on an array using JavaScript ?
In this article, we are given an array and the task is to use the filter and map function simultaneously to the given array.
JavaScript filter() method
This method returns a new array containing the elements that pass a certain test performed on an original array.
Syntax:
let newArray = oldArray.filter((currentValue, index, array) {
// Returns element to new Array
});
Parameters:
- currentValue: The current element’s value.
- index: The current element’s array index.
- array: The array object to which the current element belongs.
Return Value:
A new array object containing the filtered elements that satisfied the condition of the function
JavaScript map() method
This method is used to apply a function on every element in an array and returns a new array of the same size as the input array.
Syntax:
let newArray = oldArray.map((currentValue, index, array) {
// Returns element to new Array
});
Parameters:
- currentValue: The current element’s value.
- index: The current element’s array index.
- array: The array object to which the current element belongs.
Return Value:
It returns a new array and elements of arrays are the result of the callback function.
Approach
Firstly, by using filter() function we will retrieve those elements from an array that satisfies the given condition. As the filter() method will return the array with the required elements. Now we will apply map() method to perform the specified operations on all elements of the array returned by filter() method.
Example: In this example, we are using map and filter simultaneously on an array.
javascript
/* Printing the name of students who play basketball using filter and map method simultaneously. */ // Taking an array of Student object let students = [ { id: "001" , name: "Anish" , sports: "Cricket" }, { id: "002" , name: "Smriti" , sports: "Basketball" }, { id: "003" , name: "Rahul" , sports: "Cricket" }, { id: "004" , name: "Bakul" , sports: "Basketball" }, { id: "005" , name: "Nikita" , sports: "Hockey" } ] /* Applying filter function on students array to retrieve those students Objects who play basketball and then the new array returned by filter method is mapped in order to get the name of basketball players instead of whole object.*/ let basketballPlayers = students.filter( function (student) { return student.sports === "Basketball" ; }).map( function (student) { return student.name; }) console.log( "Basketball Players are:" ); // Printing out the name of Basketball players basketballPlayers.forEach( function (players) { console.log(players); }); |
Basketball Players are: Smriti Bakul
Contact Us