map, filter, reduce - Explained

Sure! Here's a clear breakdown of map, filter, and reduce โ€” three core JavaScript array methods that are widely used for data transformation.


๐Ÿ—บ๏ธ 1. map()

What it does:

Transforms each element in an array and returns a new array of the same length.

๐Ÿ“Œ Syntax:

js
1array.map((item, index, array) => { 2 return newItem; 3});

๐Ÿ“ฆ Example:

js
1const nums = [1, 2, 3]; 2const doubled = nums.map(n => n * 2); 3console.log(doubled); // [2, 4, 6]

๐Ÿ” Use Cases:

  • Converting data formats
  • Applying transformations (e.g., currency formatting, string formatting)

๐Ÿ” 2. filter()

What it does:

Returns a new array containing only the elements that match the given condition (predicate).

๐Ÿ“Œ Syntax:

js
1array.filter((item, index, array) => { 2 return condition; // true to keep, false to discard 3});

๐Ÿ“ฆ Example:

js
1const nums = [1, 2, 3, 4]; 2const even = nums.filter(n => n % 2 === 0); 3console.log(even); // [2, 4]

๐Ÿ” Use Cases:

  • Filtering out invalid data
  • Getting items that match criteria (e.g., isActive users)

๐Ÿงฎ 3. reduce()

What it does:

Reduces an array to a single value by applying a function to each item with an accumulator.

๐Ÿ“Œ Syntax:

js
1array.reduce((accumulator, item, index, array) => { 2 return updatedAccumulator; 3}, initialValue);

๐Ÿ“ฆ Example:

js
1const nums = [1, 2, 3, 4]; 2const sum = nums.reduce((acc, curr) => acc + curr, 0); 3console.log(sum); // 10

๐Ÿ” Use Cases:

  • Calculating totals (sum, average)
  • Grouping data
  • Building objects from arrays

๐Ÿง  Summary Table

MethodReturn ValueUse CaseMutates Original?
mapNew arrayTransform dataโŒ No
filterNew array (subset)Select specific itemsโŒ No
reduceSingle value (any)Aggregate or transform entirelyโŒ No