23 Feb 2024
Intermediate
In JavaScript, map, filter, and reduce are three commonly used array methods, each serving a distinct purpose but with some overlap in functionality. Let's delve into each of them:
-
Map:
- The
mapmethod iterates over each element of an array and applies a transformation function to each element. - It returns a new array with the results of applying the function to each element in the original array.
- The length of the returned array is the same as the original array.
- The original array remains unchanged.
- Example:
const numbers = [1, 2, 3, 4, 5]; const doubledNumbers = numbers.map(num => num * 2); // doubledNumbers is [2, 4, 6, 8, 10]
- The
-
Filter:
- The
filtermethod iterates over each element of an array and tests each element against a condition specified by a callback function. - It returns a new array containing only the elements for which the callback function returns true.
- The length of the returned array can be less than or equal to the original array.
- The original array remains unchanged.
- Example:
const numbers = [1, 2, 3, 4, 5]; const evenNumbers = numbers.filter(num => num % 2 === 0); // evenNumbers is [2, 4]
- The
-
Reduce:
- The
reducemethod iterates over each element of an array and accumulates a single result by applying a function that you provide on each element. - It takes a callback function with an accumulator and the current value being processed.
- It returns a single value, which is the accumulated result.
- The original array can be transformed into any other data type (e.g., number, string, object).
- Example:
const numbers = [1, 2, 3, 4, 5]; const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0); // sum is 15
- The
Key Differences:
-
Purpose:
map: Transform each element of an array and return a new array of the same length.filter: Select elements from an array based on a condition and return a new array.reduce: Aggregate array elements into a single value.
-
Return Value:
mapandfilteralways return new arrays.reducereturns a single value, which can be of any type.
-
Mutation:
mapandfilterdo not mutate the original array; they return new arrays.reducedoes not necessarily mutate the original array, but it depends on how you implement the reducing function.
-
Callback Function:
mapandfiltertake a callback function that defines the transformation or condition.reducetakes a callback function that defines the accumulation logic and an optional initial value.
-
Performance:
map,filter, andreduceall iterate over the array once, so their performance is generally linear with respect to the size of the array.- The actual performance difference may vary based on the specific operation and the JavaScript engine's optimizations.