🟨 JavaScript Q12 / 121

Explain map, filter, and reduce.

AI-Powered Answer ✓ Answered

In JavaScript, `map`, `filter`, and `reduce` are powerful higher-order functions available on Array.prototype. They are cornerstone methods for functional programming paradigms, enabling elegant and concise manipulation of arrays without mutating the original data.

1. Array.prototype.map()

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array. It essentially transforms each element based on a callback function, returning a new array of the same length as the original.

javascript
const numbers = [1, 2, 3, 4];
const doubledNumbers = numbers.map(number => number * 2);

console.log(doubledNumbers); // Output: [2, 4, 6, 8]
console.log(numbers);       // Output: [1, 2, 3, 4] (original array is unchanged)

In this example, map() iterates over the numbers array, multiplies each number by 2, and collects these new values into a doubledNumbers array.

2. Array.prototype.filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function. It's used to select a subset of elements from an array based on a condition, returning a new array that may be shorter than the original.

javascript
const ages = [12, 19, 20, 16, 25];
const adults = ages.filter(age => age >= 18);

console.log(adults); // Output: [19, 20, 25]
console.log(ages);   // Output: [12, 19, 20, 16, 25] (original array is unchanged)

Here, filter() iterates through the ages array, and for each age, it checks if it's 18 or greater. Only those elements satisfying the condition are included in the adults array.

3. Array.prototype.reduce()

The reduce() method executes a user-supplied 'reducer' callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result is a single output value (e.g., a number, object, or another array). It takes two arguments: a reducer function and an optional initial value for the accumulator.

The reducer function itself takes four arguments:

  • Accumulator: The accumulated value previously returned in the last invocation of the callback, or initialValue, if supplied.
  • Current Value: The current element being processed in the array.
  • Current Index (optional): The index of the current element being processed.
  • Array (optional): The array reduce() was called upon.
javascript
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);

console.log(sum);    // Output: 10
console.log(numbers); // Output: [1, 2, 3, 4] (original array is unchanged)

In this reduce() example, 0 is the initialValue for the accumulator. The callback function adds the currentValue to the accumulator in each iteration, eventually summing all numbers in the array to 10.

Key Differences and Use Cases

  • map(): Best for transforming each item in an array into a new item, resulting in a new array of the same length. Think 1-to-1 transformation.
  • filter(): Best for selecting a subset of items from an array that meet a specific condition, resulting in a new array of equal or shorter length. Think selection.
  • reduce(): Best for aggregating all items in an array into a single value (can be any data type: number, string, object, array, etc.). Think summation, counting, flattening, or grouping.