![]() |
VOOZH | about |
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.
The map() method in JavaScript creates a new array by applying a callback function to each element of the original array.
arr.map(function(args){
...
})
The filter() method in JavaScript creates a new array containing only the elements that satisfy a condition defined in a callback function.
Syntax
arr.filter(function(){
// condition
})
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.
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.
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 |