DEV Community

Amandeep Singh
Amandeep Singh

Posted on

2 2

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay