Back

Understanding Map Filter Reduce Javascript

8 Apr 2025
5 min read

The map filter and reduce in JavaScript are basic tools that can handle arrays effectively. They allow developers to filter out unwanted values, transform array elements, or aggregate data. Understanding it from a conceptual point of view is crucial for application. In this article, we will look at that with examples. 

Map: The method that helps transform each element in an array

Filter: Used to pick only the elements that match a condition

Reduce: Combines all elements into a single value

Combining the three methods can be quite powerful and useful, for example, you can filter an array, then map the filtered array, and finally reduce the mapped array.

1. JavaScript map() Method

This method in JavaScript is used to create a new array. It calls a function on each element of the array, then processes it, and then returns the updated values in the new array. Map () is used when you want to modify or transform all the elements of an array without changing the original one. It is useful when working with data manipulation tasks in map filter and reduce in JavaScript.

Syntax

array.map(function(currentValue, index, array) {  
  // code to execute  
});  

In this, the currentValue is the value of the current element being processed. The index is the index of the current element, and the array is the array on which the map() method was called.

Example

Here’s a simple example to show how map () works:

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

// Using map to double each element in the array  
const doubledNumbers = numbers.map(function(number) {  
  return number * 2;  
});  

console.log(doubledNumbers);  

Output

[ 2, 4, 6, 8, 10 ]

=== Code Execution Successful ===

In the above example, we used the map() method to multiply each number in the array by 2. The original numbers array remains the same. The doubledNumbers array contains the updated values.

2. JavaScript filter() Method

In this filter JavaScript map article, we’ll now look at the filter() method. The filter() method in JavaScript is used to create a new array with elements that pass a certain condition. It filters out the elements of an array based on the function you provide and keeps only those elements that satisfy the condition. The method is useful when working with data manipulation tasks in map filter and reduce in JavaScript.

Syntax

array.filter(function(currentValue, index, array) {  
  // condition to check  
});  

In this, the currentValue is the value of the current element being processed. The index is the index of the current element, and the array is the array on which the filter () method was called.

Example

Here’s a simple example to demonstrate how filter() works. Here, the filter() method checks each number in the array to see if it is divisible by 2. It returns a new array containing only the even numbers. And the original numbers array remains unchanged.

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

// Using filter to keep only even numbers  
const evenNumbers = numbers.filter(function(number) {  
  return number % 2 === 0;  
});  

console.log(evenNumbers);

Output

[ 2, 4 ]

=== Code Execution Successful ===

Print object having marks greater than 100  and roll greater than 5.

The filter() method can also be used to filter objects based on multiple conditions. In this example, we will filter students who have marks greater than 100 and a roll number greater than 5.

Code

let students = [ 
	{ name: "Amit", roll: 3, marks: 95 }, 
	{ name: "Sneha", roll: 7, marks: 105 }, 
	{ name: "Rohan", roll: 10, marks: 110 }, 
	{ name: "Meera", roll: 4, marks: 120 } 
]; 
 
let filteredStudents = students.filter(function(student) { 
	return student.marks > 100 && student.roll > 5; 
}); 
 
console.log(filteredStudents); 
// Output: [ { name: 'Sneha', roll: 7, marks: 105 }, { name: 'Rohan', roll: 10, marks: 110 } ]

How the code works

1. We start with an array named students, where each object contains a student's name, roll number, and marks.

2. The .filter() method is used to create a new array, filteredStudents, which includes only the students who meet both conditions:

  • Their marks should be greater than 100.
  • Their roll number should be greater than 5.

3. The callback function inside .filter() checks each student object. If both conditions are true, the student is added to filteredStudents.

4. After filtering, the new array contains only Sneha and Rohan because:

  • Sneha has 105 marks and roll 7 (both conditions met).
  • Rohan has 110 marks and roll 10 (both conditions met).

5. Finally, console.log(filteredStudents) prints the filtered students to the console.

3. JavaScript reduce() Method

Next, in this map reduce JS article, we’ll look at how to use the reduce () method. The reduce() method in JavaScript reduces an array to a single value. It executes a callback function on each array element and accumulates the result based on your provided logic. This method is very useful in map reduce js operations when calculating a sum, product, or any other aggregate value from an array.

Syntax

array.reduce(function(accumulator, currentValue, index, array) {  
  // code to execute  
}, initialValue);  

Here, 

  • accumulator: The accumulated result from the previous callback execution.
  • currentValue: The current element being processed in the array.
  • index: The index of the current element.
  • array: The array on which the reduce() method was called.
  • initialValue: A value to use as the initial accumulator value.

Example

In this example, the reduce() method starts with an initial accumulator value of 0 and adds each element of the array to it. Finally, it returns the total sum of the elements in the array. The original numbers array remains unchanged.

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

// Using reduce to calculate the sum of the numbers  
const sum = numbers.reduce(function(accumulator, number) {  
  return accumulator + number;  
}, 0);  

console.log(sum);  

Output

15

=== Code Execution Successful ===

Combining the three methods: map(), filter(), reduce()

JavaScript’s map(), filter(), and reduce() methods can be combined and used together to handle complex data transformations. Instead of using multiple loops, these methods can be chained to write code that is simple and optimised.

By using map reduce and filter in JavaScript, we can quickly process data without writing long and complex loops. This technique is widely used in nodejs map reduce tasks for handling large datasets.

Let’s see how we can apply all three methods together.

Example: Calculate the Total Marks of Students Who Scored More Than 100

We have an array of student objects, and we want to filter students who scored more than 100 marks. Then, map to extract only the marks of those students and then reduce to calculate the total sum of marks.

Code

let students = [ 
	{ name: "Amit", roll: 3, marks: 95 }, 
	{ name: "Sneha", roll: 7, marks: 105 }, 
	{ name: "Rohan", roll: 10, marks: 110 }, 
	{ name: "Meera", roll: 4, marks: 120 } 
]; 
 
let totalMarks = students 
	.filter(student => student.marks > 100)  // Step 1: Filter students with marks > 100
	.map(student => student.marks)  // Step 2: Extract only marks
	.reduce((sum, marks) => sum + marks, 0);  // Step 3: Sum the marks 
 
console.log(totalMarks); // Output: 335

How the code works

1. filter() extracts students who have marks greater than 100.

2. map() transforms the filtered objects into an array of marks.

3. reduce() sums up the marks to get the total.

Difference Between map(), filter(), and reduce() Methods

Here are the main differences between map reduce and filter in JavaScript:

Feature Map() Filter() Reduce()
Used for Transforming each element in the array and creates a new array. Filtering elements based on a condition and creates a new array. Reducing the array to a single value by applying an accumulator function.
Output A new array with transformed elements. A new array with elements that satisfy the condition. A single value (e.g., sum, product, etc.).
Callback Function Applies the function to all elements and returns the modified values. Applies the function to all elements and returns only those that pass. Applies the function to accumulate a result using all elements.
Original Array Does not modify the original array. Does not modify the original array. Does not modify the original array.

4. Javascript .forEach() Method

The .forEach() method in JavaScript is used to iterate over an array and execute a callback function for each element. Unlike map(), filter(), or reduce(), it does not return a new array. Instead it simply performs an operation on each element. This method is commonly used when we need to loop through an array and perform actions like logging values, modifying elements, or interacting with the DOM.

Syntax

array.forEach(callbackFunction(element, index, array))

Example: Print Each Element of an Array

Here, .forEach() simply goes through each element in the array and prints it.

Code

let numbers = [10, 20, 30, 40]; 
 
numbers.forEach(function(num) { 
	console.log(num); 
}); 
 
// Output: 
// 10 
// 20 
// 30 
// 40  

How the Code Works

1. We have an array named numbers containing four elements: [10, 20, 30, 40].

2. The .forEach() method is used to iterate through each element in the array.

3. The callback function inside .forEach() takes each element (num) and prints it using console.log(num).

4. The function runs for every element in the array, so the output prints each number on a new line.

5. Since .forEach() does not return a new array, it simply executes the function for each element in the original array without modifying it.

Conclusion

The map filter and reduce in javascript are important tools that simplify arrays. With it developers can write good code that can handle complex transformations, filtering, and aggregations without making errors. Mastering these methods is essential for students as they form the backbone of many real-world coding scenarios, especially in web development and data processing.

If you’re a student looking to master coding and become job-ready by the time you finish college, the CCBP 4.0 Academy program is perfect! This program offers a well-structured course designed to strengthen your coding skills, teach industry-relevant technologies, and prepare you for the future in software development and other related fields. 

Frequently Asked Questions

Here are some top JavaScript map reduce FAQs: 

1. What is the difference between filter and map in JavaScript?

The filter method in JavaScript creates a new array with elements. These elements meet a condition that you give. The map transforms each element in the array and returns a new array. Both methods are essential for efficient data manipulation in map and filter JavaScript.

2. How do map and filter in JavaScript work together?

You can combine map and filter in JavaScript to first filter elements and then modify them. For example, use a filter to remove odd numbers and then use a map to double the even ones.

3. How is node.js map reduce used for data processing?

In Node.js, the map transforms data and reduce aggregates it. Together, they are used for processing large datasets which find use in tasks like summarising values or filtering data efficiently.

4. Can we use array map reduce for complex operations?

Yes, with array map reduce, you can preprocess data with map, filter it, and then use reduce to get a single output. 

5. Why are map and filter JavaScript methods important for developers?

The filter and map in JavaScript are crucial because they make code easier to read. It enables efficient data transformation and filtering in map and filter javascript tasks.

Read More Articles

Chat with us
Chat with us
Talk to career expert