- Home
- /
- Map, Filter and Reduce
JavaScript Tutorial
IINTRODUCTION
JAVASCRIPT VARIABLES
JAVASCRIPT BASICS
JAVASCRIPT OBJECTS
DOM & BOM
OOPs
- Home
- /
- Map, Filter and Reduce
Map, Filter & Reduce
When working with arrays in JavaScript, there are three incredibly useful tools that can make your life easier and your code more elegant: map
, filter
, and reduce
. These methods are part of the modern JavaScript developer’s toolbox and help you perform complex operations on arrays without traditional loops.
Let’s explore them one by one with fresh examples.
The map() Method
The map()
function is used when you want to transform each item in an array and get back a new array of the same length. The key point is: you always get a new array.
let prices = [100, 200, 300];
let discounted = prices.map(function(price) {
return price * 0.9;
});
console.log(discounted); // [90, 180, 270]
In this example, every price is reduced by 10%. The original prices
array remains untouched.
The filter() Method
What if you only want certain items from an array based on a condition? That’s where filter()
comes in. It returns a new array with elements that pass the test you define.
let scores = [45, 76, 89, 33, 92];
let passed = scores.filter(function(score) {
return score >= 50;
});
console.log(passed); // [76, 89, 92]
Only the scores that are 50 or higher make it into the passed
array.
The reduce() Method
Unlike map
or filter
, the reduce()
method returns a single value after processing all elements. It’s great for calculating totals, finding maximums, or combining data.
let donations = [50, 100, 75, 25];
let total = donations.reduce(function(sum, amount) {
return sum + amount;
}, 0);
console.log(total); // 250
Here, we accumulate all donation amounts into one final total using reduce()
..
Combine Them for Power
These methods can also be chained together. Let’s say you want to double only the even numbers from an array and find their sum:
let numbers = [1, 2, 3, 4, 5, 6];
let result = numbers
.filter(num => num % 2 === 0) // [2, 4, 6]
.map(num => num * 2) // [4, 8, 12]
.reduce((acc, val) => acc + val); // 24
console.log(result); // 24
In one neat chain, we filtered, transformed, and summarized the data.
Wrap-up
Use
map()
to transform each item.Use
filter()
to select items based on conditions.Use
reduce()
to combine items into a single value.
These methods don’t modify the original array. They give you clean, functional programming tools to write more elegant, maintainable JavaScript code.