In JavaScript, map()
, filter()
, and reduce()
are array methods that help in transforming and processing data efficiently. They are part of the functional programming paradigm and are commonly used in modern JavaScript development.
1. map()
Method
The map()
method creates a new array by applying a function to each element of an existing array.
Syntax:
javascriptCopyEditconst newArray = array.map((element, index, array) => {
// Return the modified element
});
Key Points:
- Returns a new array with the results of applying the function to every element.
- Does not modify the original array.
Example:
javascriptCopyEditconst numbers = [1, 2, 3, 4];
const squared = numbers.map(num => num * num);
console.log(squared); // [1, 4, 9, 16]
2. filter()
Method
The filter()
method creates a new array containing only the elements that satisfy a given condition.
Syntax:
javascriptCopyEditconst filteredArray = array.filter((element, index, array) => {
// Return true to keep the element, false to discard it
});
Key Points:
- Returns a new array with elements that pass the test.
- Does not modify the original array.
Example:
javascriptCopyEditconst numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4]
3. reduce()
Method
The reduce()
method reduces the array to a single value by executing a reducer function.
Syntax:
javascriptCopyEditconst result = array.reduce((accumulator, currentValue, index, array) => {
// Return updated accumulator
}, initialValue);
Parameters:
- accumulator – Accumulates the result.
- currentValue – Current element being processed.
- initialValue – Optional initial value of the accumulator.
Key Points:
- Returns a single value.
- Useful for calculations like summing elements, flattening arrays, etc.
Example:
javascriptCopyEditconst numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // 10
Comparison Summary:
Method | Purpose | Return Value | Typical Use Case |
---|---|---|---|
map() | Transform each element in an array. | New array | Transform data (e.g., double each number). |
filter() | Filter elements based on a condition. | New array | Get a subset of elements (e.g., even numbers). |
reduce() | Reduce the array to a single value. | Single value | Aggregate data (e.g., sum, product). |
These methods make working with arrays cleaner and more readable, especially when dealing with large data transformations.