Saturday, 16 November 2024

Difference between Map(), Filter() and Reduce() in JavaScript

 In JavaScript, map(), filter(), and reduce() are high-order array methods that are commonly used to transform or process arrays. While they all work with arrays, they serve different purposes and have different behaviors. Here’s a detailed comparison:

 

1. map() – Transforming or Mapping Each Element

The map() method creates a new array populated with the results of calling a provided function on every element in the array.

 

Key Points:

  • Purpose: To transform each element of the array.

 

  • Returns: A new array of the same length as the original, with each element being the result of the function applied to the corresponding element of the original array.

 

  • Does not modify the original array.

 

Example:

    const numbers = [1, 2, 3, 4];

    const doubled = numbers.map(num => num * 2);

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

    console.log(numbers);  // [1, 2, 3, 4]  (Original array is unchanged)

 

Use Case:

  • When you want to apply a transformation to every element of an array (e.g., converting units, changing the shape of objects, etc.).

 

2. filter() – Filtering Elements Based on Condition

The filter() method creates a new array with all elements that pass a specified test (i.e., the callback function returns true for those elements).

 

Key Points:

  • Purpose: To filter out elements that don’t meet a certain condition.

 

  • Returns: A new array containing only the elements that pass the test.

 

  • Does not modify the original array.

 

Example:

    const numbers = [1, 2, 3, 4, 5];

    const evenNumbers = numbers.filter(num => num % 2 === 0);

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

    console.log(numbers);      // [1, 2, 3, 4, 5]  (Original array is unchanged)

 

Use Case:

  • When you need to filter out elements from an array based on a condition (e.g., removing invalid data, selecting items that meet specific criteria).

 

3. reduce() – Accumulating or Reducing Array to a Single Value

The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

 

Key Points:

  • Purpose: To accumulate or reduce the array elements into a single result.

 

  • Returns: A single value (it could be a number, object, array, etc.).

 

  • Does not modify the original array.

 

  • Has an accumulator (the result from the previous iteration) and a current value (the current element being processed).

 

Example:

    const numbers = [1, 2, 3, 4];

    const sum = numbers.reduce((acc, num) => acc + num, 0);

    console.log(sum);  // 10

    console.log(numbers);  // [1, 2, 3, 4]  (Original array is unchanged)

 

Explanation:

  • The reduce() method takes a callback function that is executed for each element in the array.

 

  • The callback function has two parameters: the accumulator (which starts with the initial value 0 in this case) and the current value (the element being processed).

 

  • The accumulator accumulates the result over the iterations, and the final result is returned.

 

Use Case:

  • When you need to combine or aggregate the elements of an array into a single value (e.g., summing values, flattening arrays, counting occurrences, etc.).

 

Key Differences:

Feature

map()

filter()

reduce()

Purpose

Transforms each element

Filters elements based on a condition

Reduces the array to a single value

Returns

A new array with transformed values

A new array with filtered values

A single accumulated value (any type)

Original Array

Does not modify the original array

Does not modify the original array

Does not modify the original array

Length of Result

Same length as the original array

May be shorter (if elements are filtered out)

Always a single value

Common Use Case

Transforming or modifying elements

Filtering elements based on a condition

Aggregating values (sum, average, etc.)

Callback Function

Receives the current element

Receives the current element

Receives the accumulator and current element

 

Detailed Examples of Each Method:

 

1. map() Example – Square Numbers:


    const numbers = [1, 2, 3, 4];

    const squared = numbers.map(num => num * num);

    console.log(squared);  // [1, 4, 9, 16]


2. filter() Example – Get Odd Numbers:


    const numbers = [1, 2, 3, 4, 5, 6];

    const oddNumbers = numbers.filter(num => num % 2 !== 0);

    console.log(oddNumbers);  // [1, 3, 5]


3. reduce() Example – Find the Sum of Numbers:


    const numbers = [1, 2, 3, 4];

    const total = numbers.reduce((acc, num) => acc + num, 0);

    console.log(total);  // 10

 

When to Use Each Method:


  • Use map() when you want to transform every element in an array into a new array of the same length.

 

  • Use filter() when you want to exclude certain elements from the array based on a condition.

 

  • Use reduce() when you want to aggregate all the elements in the array into a single value (e.g., sum, product, or other calculations).

 

No comments:

Post a Comment