JAVASCRIPT

What are array methods like map, filter, reduce?

In JavaScript, array methods like map, filter, and reduce are higher-order functions. They allow you to transform, filter, and combine array elements in a clean and functional way without manually writing loops.


1. map()

  • Creates a new array by applying a function to each element.
  • Does not modify the original array.

Syntax:

array.map(callback(element, index, array))

Example:

const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);

console.log(doubled);  // [2, 4, 6, 8]

2. filter()

  • Creates a new array with elements that pass a condition.
  • Useful for extracting certain elements.
  • Does not modify the original array.

Syntax:

array.filter(callback(element, index, array))

Example:

const numbers = [1, 2, 3, 4, 5, 6];
const evens = numbers.filter(num => num % 2 === 0);

console.log(evens);  // [2, 4, 6]

3. reduce()

  • Reduces the array to a single value (number, string, object, etc.).
  • Applies a function to accumulate values.
  • Can be very powerful for sums, averages, object creation, etc.

Syntax:

array.reduce(callback(accumulator, currentValue, index, array), initialValue)

Example (sum):

const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, num) => acc + num, 0);

console.log(sum);  // 10

Example (word count in array):

const fruits = ["apple", "banana", "apple", "orange", "banana"];
const count = fruits.reduce((acc, fruit) => {
  acc[fruit] = (acc[fruit] || 0) + 1;
  return acc;
}, {});

console.log(count);  
// { apple: 2, banana: 2, orange: 1 }

Quick Comparison

MethodReturnsUse case
map()New array (same length)Transform each element
filter()New array (subset)Select elements based on condition
reduce()Single value (any type)Combine elements into one
No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *