Sobes.tech
Middle+

How do the MAP, FILTER, REDUCE, and FOREACH array methods differ from each other? What are they used for?

sobes.tech AI

Answer from AI

All these methods are higher-order functions for working with arrays in JavaScript, but they serve different purposes:

  • map — transforms each element of the array and returns a new array with the results. Used when you need an array of the same length but with modified elements.

  • filter — selects only those elements from the array that satisfy a condition, returning a new array with the filtered elements.

  • reduce — reduces the array to a single value by accumulating the result through an accumulator function. For example, summing, counting, or building an object.

  • forEach — simply executes a function for each element of the array without returning a new array. Used for side effects, such as logging to the console or modifying external variables.

Example:

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

const doubled = numbers.map(n => n * 2); // [2, 4, 6, 8]
const evens = numbers.filter(n => n % 2 === 0); // [2, 4]
const sum = numbers.reduce((acc, n) => acc + n, 0); // 10
numbers.forEach(n => console.log(n)); // outputs 1, 2, 3, 4
How do the MAP, FILTER, REDUCE, and FOREACH array… - sobes.tech