Explain map, filter and reduce methods with an example

Explain map, filter and reduce methods with an example

Apr 24, 2023 | Javascript

map(), filter(), and reduce() are three important array methods in JavaScript. They allow us to perform complex operations on arrays with concise, functional-style code.

Here are some examples of how these methods work:

map(): The map() method creates a new array by calling a function on each element of the original array. It returns an array of the same length as the original array, but with each element transformed by the function.

Example:

const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(num => num * 2);
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]

In this example, the map() method is used to create a new array doubledNumbers with each element of the original array numbers multiplied by 2.

filter(): The filter() method creates a new array by filtering out elements from the original array based on a condition specified in a callback function. It returns an array with only the elements that meet the condition.

Example:

const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]

In this example, the filter() method is used to create a new array evenNumbers with only the even numbers from the original array numbers.

reduce(): The reduce() method reduces an array to a single value by calling a function on each element of the array and accumulating the result. It takes two arguments: a callback function and an initial value for the accumulator.

Example:

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

In this example, the reduce() method is used to calculate the sum of all elements in the numbers array. The accumulator acc is initialized to 0, and the callback function adds each element of the array num to the accumulator acc until all elements have been processed.

These array methods are powerful tools for working with arrays in JavaScript and can help to make your code more concise and expressive.

 

Being Idea is a web platform of programming tutorials to make better programming skills and provides Software Development Solutions.

0 Comments

Leave a Reply