Intro
map
and filter
are array methods in JavaScript used for processing arrays, but they serve different purposes and have distinct functionalities.
Points of Contrast:
-
Transformation vs. Selection:
- Map: Transforms each element of the array using a provided function.
- Filter: Selects elements from the array based on a condition.
- Output:
- Map: Returns an array with the same length, containing transformed elements.
- Filter: Returns an array containing only elements that meet the condition.
- Usage of Callback Function:
- Map: Callback function returns a value for each element.
- Filter: Callback function returns a boolean for each element.
Real-World Usage:
map
Usage:- Transforming Data.
- Extracting Properties.
- Generating UI Components.
filter
Usage:- Filtering Data.
- Removing Empty Values.
- Data Validation.
Code snippet:
// Example array const numbers = [1, 2, 3, 4, 5]; // map example: square each number
const squaredNumbers = numbers.map(num => num * num);
console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]
// filter example: select even numbers
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]
In summary, map
and filter
are essential for processing arrays in JavaScript, with map
used for transforming data and filter
used for selecting elements based on conditions.