Map, Filter & Reduce Functions in JavaScript

Map, Filter & Reduce Functions in JavaScript

Unleashing the Power of Map, Filter, and Reduce Functions

Play this article

Introduction

Map, filter, and reduce are three of the most useful and powerful high-order array methods!

If you want to master React a greater understanding of these methods will help you in your learning journey as these methods are used pretty much everywhere in React.

In this article, We'll learn about these methods with examples! But before we start, check the fun summary by Steven Luscher:

Don't worry if you didn't get it! After completing this blog you'll be able to understand this Tweet!

So, With that let's start our learning!

Map() method:

This method is very important for React as well. The Map method creates a new array and implements the function on every element of that array.

Syntax:

Arrays.map((element, index, array) => { ... })

Map method can have 3 arguments, but most of the time we'll be working with element value only!

Let's understand the workings of this method with some examples!

We'll take a demo array and apply a double function in it!

const demo = [1, 2, 3, 4, 5];

const newArr = demo.map((element)=> {
    return element*2; //doubles every element
})

console.log(newArr);
//output: [2,4,6,8,10];

Now it's clear to us what map() does! Right?

If so then try to do the following problem yourself and write the answers in the comments!

//   Given an array of names in lowercase, capitalize the first letter of each name and return a new array with the capitalized names.

function capitalizeNames(names) {
  // Use the map() method to capitalize each name and return a new array.
  // Your code here...
}

const namesArray = ["john", "alice", "bob"];
const capitalizedNames = capitalizeNames(namesArray);

console.log(capitalizedNames); // Expected output: ["John", "Alice", "Bob"]

Filter() Method:

As the name suggests filter function method filters the elements from an array based on a given condition. It creates a new array and adds the elements that satisfy the condition provided.

Syntax:

Array.filter((element, index, array) => { ... } )

Just like the map(), filter() method can have 3 arguments. But Unlike map() the return type of the callback function is boolean. It returns a new array that contains only the elements for which the callback function returns true .

Let's see one example:

const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter((number) => number % 2 === 0);
// evenNumbers is [2, 4]

In this example filter method only adds the numbers that are even. So it's pretty clear how the filter method works!

Now, Solve the following problem to solidify your concepts!

//Q. Given an array of numbers, filter out all the numbers that are greater than or equal to 10 and return a new array containing only the filtered numbers.

function filterNumbersGreaterThanTen(numbers) {
  // Use the filter() method to create a new array containing
  // only numbers greater than or equal to 10.
  // Your code here...
}

const inputArray = [5, 12, 8, 15, 3, 10];
const filteredNumbers = filterNumbersGreaterThanTen(inputArray);

console.log(filteredNumbers); // Expected output: [12, 15, 10]

Reduce() Function:

Among these three methods, Reduce() is the least used one! folks often find it hard to understand this reduce() method!

But don't worry! We'll learn it by doing!

So, In simple words reduce() method is used to "reduce" an array to a single value. it iterates through the elements of the array and calculates the result based on the given condition.

Syntax:

reduce((accumulator, current, index, array) => { ... }, initialValue)

Oh! The syntax looks pretty complex! Okay so let's understand it with some examples!

Suppose we want to add all elements of the array using reduce() method! So the code for that will be:

const numbers = [1, 2, 3, 4, 5];

const sum = numbers.reduce(
(accumulator, currentValue) => accumulator + currentValue, 
0);

console.log(sum); 
// Output: 15

But How it works?

let's see how the value changes in each iteration, then it will be easier to understand! To do that we'll add one line to the previous code!

const numbers = [1, 2, 3, 4, 5];

const sum = numbers.reduce((accumulator, currentValue) => {
  console.log(`accumulator: ${accumulator}, currentValue: ${currentValue}`);
  return accumulator + currentValue;
}, 0);

We'll get this in the console:

With this, we can easily understand how reduce() method is working! The accumulator starts with the initial value of 0, and with each iteration, it adds the currentValue to it. Finally, the sum variable holds the accumulated value, which is 15 in this case.

Conclusion

If you found this blog post helpful, please consider sharing it with others who might benefit. You can also follow me for more content on Javascript, React, and other web development topics.

To sponsor my work, please visit: Arindam's Sponsor Page and explore the various sponsorship options.

Connect with me on Twitter, LinkedIn, Youtube and GitHub.

Thank you for Reading :)

Did you find this article valuable?

Support Arindam Majumder by becoming a sponsor. Any amount is appreciated!