How to use map and filter simultaneously on an array using JavaScript ?
Last Updated :
20 Dec, 2023
In this article, we are given an array and the task is to use the filter and map function simultaneously to the given array.
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
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
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" }
]
let basketballPlayers = students.filter( function (student) {
return student.sports === "Basketball" ;
}).map( function (student) {
return student.name;
})
console.log( "Basketball Players are:" );
basketballPlayers.forEach( function (players) {
console.log(players);
});
|
Output
Basketball Players are:
Smriti
Bakul
Share your thoughts in the comments
Please Login to comment...