Difference Between Reduce(), Map() and Filter()

SHAURYA ROYSHAURYA ROY
2 min read

Table of contents

Have you ever found yourself tangled in the web of map(), filter(), and reduce() in JavaScript? Don't worry; you're not alone. These three array methods are powerful tools for manipulating data, but understanding when and how to use them can be a bit perplexing at first. Let me share my journey of confusion and enlightenment with these functions.

Have you ever found yourself tangled in the web of map(), filter(), and reduce() in JavaScript? Don't worry; you're not alone. These three array methods are powerful tools for manipulating data, but understanding when and how to use them can be a bit perplexing at first. Let me share my journey of confusion and enlightenment with these functions.

The Confusion Begins

When I first encountered map(), filter(), and reduce(), I couldn't quite grasp the differences between them. They all seemed to do similar things - transforming arrays in some way. I found myself using them interchangeably, leading to messy code and confusion.

After some trial and error, I finally had my "aha" moment. Here's a breakdown of each function and how they differ:

  1. map(): This function creates a new array by applying a callback 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 the callback function.

  2. filter(): Filter, as the name suggests, creates a new array with all elements that pass a test implemented by the provided function. It returns an array containing only the elements that satisfy the condition specified in the callback function.

  3. reduce(): Reduce is a bit different; it applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value. It's like folding or accumulating values into one final result.

So next time you find yourself confused between these functions, remember their distinct roles and choose wisely based on your specific needs.

Also this was my first blog. Will be posting more such on a weekly basis.

0
Subscribe to my newsletter

Read articles from SHAURYA ROY directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

SHAURYA ROY
SHAURYA ROY