In JavaScript, map, filter, and reduce are array functions used to perform transformations on arrays. Each of these functions serves a different purpose:

  1. map:
    The map function is used to create a new array by applying a transformation function to each element of the original array. It returns a new array with the same length as the original, where each element is the result of applying the provided function to the corresponding element in the original array.

Syntax:

const newArray = originalArray.map((element, index, array) => {
  // Transformation logic goes here
  return transformedElement;
});

Example:

const numbers = [1, 2, 3, 4];
const doubledNumbers = numbers.map((num) => num * 2);
// doubledNumbers is now [2, 4, 6, 8]
  1. filter:
    The filter function is used to create a new array containing only the elements that pass a test (predicate) specified by a provided function. It returns a new array with the elements for which the function returns true.

Syntax:

const newArray = originalArray.filter((element, index, array) => {
  // Test logic goes here
  return trueOrFalse; // Return true to include the element in the new array, false to exclude it.
});

Example:

const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter((num) => num % 2 === 0);
// evenNumbers is now [2, 4, 6]
  1. reduce:
    The reduce function is used to “reduce” an array to a single value by applying a function to each element of the array. It accumulates the result as it iterates through the array.

Syntax:

const result = originalArray.reduce((accumulator, element, index, array) => {
  // Accumulation logic goes here
  return updatedAccumulator;
}, initialValue);

Example:

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

In summary, map is used for transforming elements, filter for selecting elements based on a condition, and reduce for aggregating elements into a single value. Understanding when to use each of these functions can greatly simplify and enhance the processing of arrays in JavaScript.

Leave a Reply

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