The map(), filter(), and reduce() methods are powerful JavaScript array functions that help transform and process data efficiently. They allow you to apply custom logic to arrays in a clean, functional programming style.
- map() creates a new array by applying a function to each element.
- filter() returns a new array containing only elements that meet a condition.
- reduce() combines all elements into a single value (like a sum or object).
1. JavaScript map() Method
The map() method in JavaScript creates a new array by applying a callback function to each element of the original array.
- Iterates through every element of the array
- Executes the callback function for each element
- Stores the returned value in the new array
arr.map(function(args){
...
})
let arr= [2, 4, 8, 10]
let updatedArr = arr.map(val=> val+2)
console.log(arr);
console.log(updatedArr);
2. JavaScript filter() Method
The filter() method in JavaScript creates a new array containing only the elements that satisfy a condition defined in a callback function.
- Iterates over each element of the array
- Includes elements when the callback returns true
- Excludes elements when the callback returns false
Syntax
arr.filter(function(){
// condition
})
let arr = [2, 4, 8, 10];
let updatedArr = arr.slice().filter(val => val < 5);
console.log(arr);
console.log(updatedArr);
3. JavaScript reduce() Method
The reduce() in JavaScript is used to combine all elements of an array into a single value by applying a callback function to each element.
- Accumulator: stores the result after each iteration
- currentValue: the current element being processed
- currentIndex: index of the current element
Syntax
arr.reduce(function(){
...
})
Example: The code creates an array [2, 4, 8, 10] and uses reduce() to sum its elements, but it throws an error due to an incorrect accumulator expression and the absence of an initial value.
- curr is wrongly reassigned as prev and curr instead of returning the sum
- No initial accumulator value is provided
- This leads to an error during the reduce() operation
let arr= [2,4,8,10]
let updatedArr = arr.reduce((prev, curr)=> curr= prev+curr)
console.log(arr);
console.log(updatedArr);
Difference Between map(), filter(), and reduce() Methods
map() | filter() | reduce() |
|---|---|---|
| Returns a new array | Returns a new array | Returns a single element |
| Modifies each element of the array | Filter out the element which passes the condition | Reduces array to a single value |
| Uses value, index, array | Uses current value, index, array | Uses Previous value and current value |