DEV Community

Cover image for Understanding Map, Filter & Reduce functions.
Kelsy Mnk
Kelsy Mnk

Posted on • Updated on

Understanding Map, Filter & Reduce functions.

If you still don't feel comfortable with these functions or simply need a refresher, well you are at the right place :)


Before we jump in, I'd like to talk about what these functions have in common. Can you take a guess? They are both referred to as Higher-Order Functions.

What's a higher-order function?

A higher-order function (HOF) is a function that can take another function as an argument or that can return a function as its result. All other functions are simply First-Order Functions.

Why use a HOF? πŸ€”

It allows us to keep our code DRY and more flexible. (Let me know if you are interested to know HOF more in-depth :-)

Higher-order functions

Alright, now that we have some background let's start, shall we?


.Map()

The map() method performs a callback function on each element in an array. It will return a new array from the returned values so that the initial array can stay unmodified.

Let's take a look :)

const test = [1,3,-4,5,9,2]
const newTest = test.map(function (x) {
      return x*x;
});
console.log(newTest);

// output: [1,9,16,25,81,4]
Enter fullscreen mode Exit fullscreen mode

So what we did here was, multiply each number by itself inside the test array then return the value inside a new array.

Alright, now I'm sure we can write this function on a single line to make it a little bit cleaner :)

Cleaner code πŸ‘‡

const test = [1,3,-4,5,9,2]
const newTest = test.map((x) => x*x);
console.log(newTest);

// Output: [1,9,16,25,81,4]
Enter fullscreen mode Exit fullscreen mode

.Filter()

As the name suggests 'filter', it will allow you to filter a range of data based on the given conditions.

Similarly to the map function, the .filter() will also perform a callback function on each element in an array. Then, using a true or false condition, it will return a new array filled with elements that are true to that condition.

For example:

const score = [1,2,9,6,3,-8]
const newScore = score.filter(function (x) {
        return x%2 === 0; 
});
console.log(newScore);

// Output: [2,6,-8]
Enter fullscreen mode Exit fullscreen mode

In this example, we wanted to filter out all the odd numbers and then return only even numbers.
Is 1 true to the condition? No, so don't return it.
Is 2 true to the condition? Yes, then return it.
And so on...

This function can also be written on a single line. Can you give it a shot? :)


.Reduce()

The .reduce() method iterates through an array and returns a single value.

It takes a callback function with two parameters (accumulator, currentValue) as arguments. The accumulator is the value returned from the previous iteration and the currentValue is the current element being processed in the array.

Let's take an example.

const numbers = [1,3,7,4,5]
const totalNumbers = numbers.reduce(function (acc, currVal) {
        return acc + currVal;
}, 0); //initializing the accumulator to 0
console.log(totalNumbers);

// Output: [20]
Enter fullscreen mode Exit fullscreen mode

So here, we summed all elements of the array and then returned a single value (where the output is 20). In other words, reducing the array to a single value.

Great! Now that we've learned these functions, let's take a quick look at the summary :-)


Summary

.Map()

  • Performs a callback function on each element in an array.
  • Creates a new array from the callback function.
  • Does not change the original array.
  • Does not execute the function for empty elements.

.Filter()

  • Performs a callback function on each element in an array.
  • Creates a new array filled with elements that passed the true/false condition based on the given instructions.
  • Does not change the original array.

.Reduce()

  • Returns a single value (using the accumulator).
  • Executes a reducer function for an array element.
  • Does not change the original array.

Before we wrap this up, feel free to check in the comment for some additional information written by some awesome users from this community :) You can add some details too if you think I might've missed something ;)

Hope you enjoyed this article ❀️

That's it! This was a quick refresher for the map, filter & reduce functions. Feel free to bookmark this if you'd like to come back at it in the future.

Let me know if you enjoyed it by leaving a like or a comment :) or if there is a topic that you'd like me to write about.

Thanks for your time,

Happy coding :)

Top comments (4)

Collapse
 
tracygjg profile image
Tracy Gilmore • Edited

Thought the reader might also like to know the callback functions have specific names.

For map the callback is called a transform because it transforms a value from the input array into a new value for the output array.

A function that returns a Boolean value, such as the filter callback, is typically called a predicate function. The same applies for the Array methods: some, every, find and findIndex etc.

Finally the callback supplied to a reduce method is called a reducer because it takes in two values (running value and array item in this case) and reduces the to a single output.

However, many of the Array methods call supply the callback with two additional arguments, the index of the item in the array and the source array itself.

Collapse
 
klc profile image
Kelsy Mnk

Oh what a great info:) Thanks, really appreciate it!

Collapse
 
weaves87 profile image
Andrew Weaver

Great writeup! πŸ‘

These are concepts that exist across most any modern language these days, so they're useful to know.

I still see a lot of people performing the functions these particular functions do using loops they manually write themselves.

One of the benefits about using these functions instead is that they don't alter the original array - they treat it as immutable. This really helps when code complexity increases, and you need to debug an issue somewhere: it makes it far easier to track the state as it changes over time, which leads to bugs being much easier to spot and fix.

Collapse
 
klc profile image
Kelsy Mnk

Thank you:)

This is a great additional information, thanks for making it a little bit more clear✨.