DEV Community

Amandeep Singh
Amandeep Singh

Posted on

The big 3 of array methods - map, filter & reduce

Hi there,
These array methods are the most important part of functional programming in JavaScript. I'm pretty sure if you're building a project in JS, you're gonna use atleast one of these, if not all.

So, let's get started!

Sample array:
const arr = [2, 4, 6, 8, 10]

map()

It creates a new array with the results of calling a function for every array element.

const mapped = arr.map((element, index) => element * index);
//creates an array, multiplying every element of the original array with its index.

console.log(mapped);
// Outputs: [0, 4, 12, 24, 40]
Enter fullscreen mode Exit fullscreen mode

filter()

It creates a new array filled with all array elements that pass a test (provided as a function).

const filtered = arr.filter((element, index) => element % 4 === 0);
//creates an array, filtering the original array with elements divisible by 4. 

console.log(filtered);
// Outputs: [4, 8]
Enter fullscreen mode Exit fullscreen mode

reduce()

It reduces the array to a single value, executing a provided function for each value of the array (from left-to-right).

const reduced = arr.reduce((sum, current) => sum + current, 0);
//calculates sum of all the array elements

console.log(reduced);
// Outputs: 30
Enter fullscreen mode Exit fullscreen mode

Top comments (0)