Why should you master the trio of map, filter, and reduce in JavaScript?

Why should you master the trio of map, filter, and reduce in JavaScript?

Daily short news for you
  • A software that converts text to speech created by a Vietnamese programmer - J2TEAM - Text to Speech (Free). You can convert dozens of languages into dozens of different natural voices. The special thing is that it is free.

    In preliminary evaluation, the conversion of long texts or texts in pure Vietnamese is very good. However, when it includes English words, it sounds a bit funny 😅

    » Read more
  • How terrifying, Codeium - known as a competitor to Github Copilot, as it allows users to use it for free without limits. Recently, they introduced the Windsurf Editor - no longer just a VSCode Extension but a full Editor now - directly competing with Cursor. And the main point is that it... is completely free 🫣.

    » Read more
  • There is a rather interesting study that I came across: "Users never bother to read things they don't want to." (That's a bold statement, but it's more true than not. 😅)

    Don't believe it? I bet you've encountered situations where you've clicked on a button repeatedly and it doesn't respond, but in reality, it has displayed an error message somewhere. Or you've filled out everything and then when you hit the submit button, it doesn't go through. Frustrated, you scroll up or down to read and find out... oh, it turns out there's an extra step or two you need to take, right?

    It’s not far from the blog here. I thought that anyone who cares about the blog would click on the "Allow notifications" button just below the post. But the truth is, no one bothers to click it. Is it because they don't want to receive notifications? Probably not! I think it's because they just didn’t read that line.

    The evidence is that only when a notification pops up and takes up half the screen, or suddenly appears to grab attention, do they actually read it—and of course, it attracts a few more subscribers—something that was never achieved before.

    » Read more

The Problem

Data stored in a database often needs to be normalized to reduce size and improve query speed. Therefore, after retrieving data, it often needs to undergo multiple data transformations before it can be further processed.

In frontend programming, especially in programming based on modern frameworks such as Angular, React, Vue, creating objects to store the state of the application requires even more data manipulation capabilities. This is because these states constantly change depending on the display logic and user interactions.

Such data is often stored in objects or arrays, which is why the trio of map, filter, and reduce were introduced since ES5 to help us manipulate array data in a much more useful way.

map, filter, and reduce

The map function iterates over an array and returns a new array with the same number of elements. The elements are returned through the return statement.

Example:

const arr = [1, 2, 3];
const arr2 = arr.map(function (item) {
  return item + 1;
});
// [2, 3, 4]

The filter function also iterates over an array and returns a new array with elements that satisfy a true/false condition.

Example:

const arr = [1, 2, 3];
const arr2 = arr.map(function (item) {
  return item > 1;
});
// [2, 3]

Reduce iterates over an array and performs calculations in the callback function.

Example:

const arr = [1, 2, 3];
const sum = arr.reduce(function(accumulator, currentValue) {
  return accumulator + currentValue;
}, 0);

reduce is a more advanced function, so it has a higher level of difficulty to start with. However, you can quickly master them through a few examples at Reduce Syntax.

The full syntax of reduce is:

reduce((accumulator, currentValue, currentIndex, array) => {
    /* … */
}, initialValue)

Where accumulator is the accumulated value, the initial accumulated value is equal to initialValue, currentValue is the element in the array at the current iteration, currentIndex is the position of the element, and array is the original array. initialValue is the initial value.

The output of map and filter is always an array, so if you see them, the output must be something that can be iterated over. This is very important because it helps create consistency and seamless integration when combining multiple functions for processing.

const arr = [];
arr.map().filter().map()...  

You can use filter immediately after map without worrying that the result of map returns null, undefined, or anything that "cannot be iterated" over.

Some Use Cases

There are many cases where you need to use this trio. Use map when you need to add/modify or change properties in an array. Use filter when you need to filter data in an array. Finally, use reduce when you want to aggregate a result from an array.

In summary, when working with array data, always think of this trio first, and gradually you will learn to use them masterfully. This helps you write shorter code.

One typical use case I use them for is when processing data received from an API. The data received from an API is "raw" data, so it needs to go through a few more steps of processing before it becomes "clean" data that can be displayed on a web page. At that time, we can use map, filter, or reduce to add, remove, modify, or filter data in the array.

Another use case is when retrieving data from a database. This data is optimized for storage, so while processing the logic, you still need to add or modify a lot to get the standard data. A typical example for this case is reformatting the data returned to the client through the API.

The third case is data created to serve the purpose of processing logic. This type of data is created during the process of solving a specific problem. Data transformation can occur frequently during computation. Mastering map, filter, and reduce can help you solve these problems with less code.

In addition, there are many array functions that JavaScript provides when operating on arrays such as find, findIndex, indexOf, etc. These functions can be completely replaced by the trio of map, filter, and reduce. However, if possible, use them to increase transparency in the code.

Conclusion

The trio of map, filter, and reduce is a powerful tool when working with array data. Knowing how to use them appropriately helps you save time writing code and makes your code more concise.

Premium
Hello

The secret stack of Blog

As a developer, are you curious about the technology secrets or the technical debts of this blog? All secrets will be revealed in the article below. What are you waiting for, click now!

As a developer, are you curious about the technology secrets or the technical debts of this blog? All secrets will be revealed in the article below. What are you waiting for, click now!

View all

Subscribe to receive new article notifications

or
* The summary newsletter is sent every 1-2 weeks, cancel anytime.
Author

Hello, my name is Hoai - a developer who tells stories through writing ✍️ and creating products 🚀. With many years of programming experience, I have contributed to various products that bring value to users at my workplace as well as to myself. My hobbies include reading, writing, and researching... I created this blog with the mission of delivering quality articles to the readers of 2coffee.dev.Follow me through these channels LinkedIn, Facebook, Instagram, Telegram.

Did you find this article helpful?
NoYes

Comments (0)

Leave a comment...