map, filter, reduce - Explained
Sure! Here's a clear breakdown of map
, filter
, and reduce
โ three core JavaScript array methods that are widely used for data transformation.
๐บ๏ธ 1. map()
What it does:
Transforms each element in an array and returns a new array of the same length.
๐ Syntax:
๐ฆ Example:
๐ Use Cases:
- Converting data formats
- Applying transformations (e.g., currency formatting, string formatting)
๐ 2. filter()
What it does:
Returns a new array containing only the elements that match the given condition (predicate).
๐ Syntax:
๐ฆ Example:
๐ Use Cases:
- Filtering out invalid data
- Getting items that match criteria (e.g., isActive users)
๐งฎ 3. reduce()
What it does:
Reduces an array to a single value by applying a function to each item with an accumulator.
๐ Syntax:
๐ฆ Example:
๐ Use Cases:
- Calculating totals (sum, average)
- Grouping data
- Building objects from arrays
๐ง Summary Table
Method | Return Value | Use Case | Mutates Original? |
---|---|---|---|
map | New array | Transform data | โ No |
filter | New array (subset) | Select specific items | โ No |
reduce | Single value (any) | Aggregate or transform entirely | โ No |