JavaScript Array Magic: Crack .map(), .filter(), and .reduce() with Examples

Every JavaScript developer comes across these powerful higher-order functions: .map(), .filter(), and .reduce(). But before diving into how they work, let’s step back and understand what each one actually does. By the end of this article, you’ll not only know how to use them confidently but also have a handy reference you can come back to anytime
And don’t worry if you’re not fully sure what higher-order functions are — as we go through the examples, you’ll naturally get a sense of it.
Higher Order Functions
In simple terms, higher-order functions are just functions that take another function as an argument.
(If you’re coming from a different programming language, this might sound like — wait, what the hell? — but stick with me!)
For now, don’t worry about the deep mechanics. Just remember:
✅ A function taking another function — that’s all a higher-order function is.
Here’s a quick example to make it clearer:
function greetUser(name, anotherFunction) {
console.log("Hello " + name);
anotherFunction(); // Calling the function passed as argument
}
function showWelcomeMessage() {
console.log("Welcome to the blog!");
}
// Calling the higher-order function
greetUser("Jyotir", showWelcomeMessage);
//OUTPUT
/* Hello Jyotir
Welcome to the blog! */
See that? greetUser takes showWelcomeMessage as a parameter — boom, that’s a higher-order function!
.Map() 🤯
Imagine this — you have an array of numbers, and you want to double each number. If you didn’t know about .map(), you would probably write something like this:
let arr = [2,4,3,6,10];
let output = [];
for(let i = 0; i < arr.length; i++){
output.push(arr[i]*2);
}
console.log(output); // [4, 8, 6, 12, 20]
Now this is fine ,but remember the higher-order function we saw earlier? Well, .map() makes your life way easier when you want to transform each item in an array.
let arr = [2,4,3,6,10];
let output = arr.map(function (item)=> {
return item * 2;
})
console.log(output); // [4, 8, 6, 12, 20]
Think of .map() like this:
You give
.map()a list of items (the array).You also give it a machine (the function) that knows what to do with each item.
.map()runs all the items through the machine and gives you a new array with transformed items.
What just happened?
Let’s break it down (this will stick in your head forever — promise):
✅ .map() is a higher-order function because it takes a function as a parameter.
✅ This function (often called a callback function) runs once for each item in the array.
✅ Inside this function, you get each item one-by-one (that’s the item).
✅ Whatever this function returns, .map() collects into a new array.
✅ So, for arr[0] = 2, the function runs and returns 2 * 2 = 4. Same for all other items.
When should we use .map()? (with examples)
Use .map() whenever you want to transform each item in an array — meaning you want to perform some operation on every item and return a new array with the transformed items.
Here are some examples to make this super clear:
// Example 1: Double every number
let numbers = [1, 2, 3, 4, 5];
let doubled = numbers.map(num => num * 2); // shorter syntax no need of writing return
console.log(doubled); // [2, 4, 6, 8, 10]
// Example 2: Add "Mr." to every name
let names = ["John", "Doe", "Jane"];
let updatedNames = names.map(name => "Mr. " + name);
console.log(updatedNames); // ["Mr. John", "Mr. Doe", "Mr. Jane"]
// Example 3: Extract specific property from objects
let users = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 35 }
];
let namesOnly = users.map(user => user.name);
console.log(namesOnly);// ["Alice", "Bob", "Charlie"]
.Filter() — Does it filter stuff? 😎
Yes! It does exactly what the name suggests — it filters stuff!
Imagine you have a list of people, and you only want the ones above 40 years old.
Before .filter() existed (or before you knew about it), you might have written this:
let people = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 45 },
{ name: "Charlie", age: 35 },
{ name: "David", age: 50 }
];
let aboveForty = [];
for (let i = 0; i < people.length; i++) {
if (people[i].age > 40) {
aboveForty.push(people[i]);
}
}
console.log(aboveForty); // [{ name: "Bob", age: 45 }, { name: "David", age: 50 }]
But now, with the help of .filter(), this becomes much cleaner and way more readable:
let people = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 45 },
{ name: "Charlie", age: 35 },
{ name: "David", age: 50 }
];
let aboveForty = people.filter(function logic(person) {
if (person.age > 40) {
return true; // Only those who pass this test stay in the new array
}
});
console.log(aboveForty); //[{ name: "Bob", age: 45 },{ name: "David", age: 50 }]
✅ No manual looping
✅ No need to handle your own push
✅ Just write the logic, and .filter() takes care of the rest!
🔍 What just happened? What kind of magic is this?
The logic function inside .filter() runs on each item (person) of the people array.
If the function returns true, that item is automatically added to
aboveForty.If it returns false, that item is ignored.
No need to manually loop, check conditions, or push items into a new array—.filter() does it all for you!
🎯 Shorter version using an arrow function
let people = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 45 },
{ name: "Charlie", age: 35 },
{ name: "David", age: 50 }
];
let aboveForty = people.filter(person => person.age > 40);
console.log(aboveForty);
When should we use .filter()? (with examples)
Whenever you want to pick only certain items from an array based on some condition — .filter() is your go-to hero! It returns a new array with only the items that passed the test (items where your function returned true).
Here are some super-clear examples to lock this into your brain:
// Example 1: Find numbers greater than 50
let numbers = [10, 55, 23, 78, 92, 15];
let greaterThanFifty = numbers.filter(num => num > 50);
console.log(greaterThanFifty); // [55, 78, 92]
// Example 2: Filter completed tasks from a to-do list
let tasks = [
{ title: "Learn .map()", completed: true },
{ title: "Learn .filter()", completed: false },
{ title: "Write blog", completed: true }
];
let completedTasks = tasks.filter(task => task.completed);
console.log(completedTasks);
.Reduce() - Does it reduce the array ? 😥
Kinda of yes , lets learn this by example, theory can only take you up to a level
What problem does .reduce() solve?
Imagine you have a list of numbers, and you want to find the total sum. Without .reduce(), you’d probably do something like this:
let numbers = [10, 20, 30, 40];
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
console.log(sum); // 100
Enter .reduce()
let numbers = [10, 20, 30, 40];
let sum = numbers.reduce(function sumAll(accumulator, currentElement) {
accumulator = accumulator + currentElement;
return accumulator;
}, 0);
console.log(sum); // 100
Now, I know .reduce() feels a bit more complicated than .map() and .filter(), so let’s break it down piece by piece — no rush, we’ll get this sorted.
What is an accumulator? 🤔
The accumulator is exactly what the name says — it collects and builds up a value as .reduce() loops through the array. Think of it like the sum variable we used in the old-school for loop. Each time the loop runs, the accumulator grows.
What is currentElement?
This one’s easy — it’s just the current item in the array, exactly like in .map() and .filter().
What’s that second parameter (the 0)?
That’s the initial value of the accumulator. Think of it like when you do:
let sum = 0;
This 0 is the starting point. If you were finding the product of all numbers, you might start with 1. For a string concatenation, you could start with an empty string ("").
Here’s that full pattern again:
array.reduce(callbackFunction, initialValue)
The callbackFunction gets 2 main arguments:
accumulator— the running total (or combined value so far)currentElement— the current item from the array
Bringing it all together
Let’s rewrite the earlier example with better clarity:
let numbers = [10, 20, 30, 40];
let sum = numbers.reduce(function (accumulator, currentElement) {
return accumulator + currentElement;
}, 0);
console.log(sum); // 100
| Step | Current Number (num) | Accumulator (acc) |
| Initial | - | 0 |
| 1 | 10 | 0 + 10 = 10 |
| 2 | 20 | 10 + 20 = 30 |
| 3 | 30 | 30 + 30 = 60 |
| 4 | 40 | 60 + 40 = 100 |
This is almost the same as:
let sum = 0; for(let i = 0; i < numbers.length; i++) { sum = sum + numbers[i]; }
Key takeaway 🚀
✅ .reduce() can do way more than just sums — you can use it to build arrays, objects, or even filter things if you want to get creative!
✅ That initial value is crucial — it sets the tone for your accumulator.
✅ If you master .reduce(), you unlock a whole new level of array wizardry.
When should we use .reduce()? (with examples)
Use .reduce() when you want to boil down an array into a single value.
This "single value" could be:
✅ A sum (like we saw before)
✅ A product (multiplying everything together)
✅ A single object (combining data into one object)
✅ Even a new array (yup, .reduce() can do that too!)
// Example 1: Sum all numbers
let numbers = [10, 20, 30, 40];
let sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 100
// Example 2: Find the maximum number
let numbers = [5, 8, 2, 9, 3];
let max = numbers.reduce((acc, num) => {
return num > acc ? num : acc;
}, numbers[0]); // Start with first element as initial value
console.log(max); // 9
// Example 3: Group items by property (a little advance!)
let people = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 45 },
{ name: "Charlie", age: 35 },
{ name: "David", age: 25 }
];
let groupedByAge = people.reduce((acc, person) => {
if (!acc[person.age]) {
acc[person.age] = [];
}
acc[person.age].push(person.name);
return acc;
}, {});
console.log(groupedByAge);
// Output:
// {
// 25: ["Alice", "David"],
// 45: ["Bob"],
// 35: ["Charlie"]
// }
One-Liner Summary 📚
| Use This | When You Want To |
.map() | Transform each item into something new |
.filter() | Pick some items (based on a condition) |
.reduce() | Combine everything into one final result |
Chaining Higher-Order Functions (.map(), .filter(), .reduce())
Chaining means you call multiple methods one after the other on the same array. Each method passes its result to the next method in the chain.
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let result = numbers
.filter(num => num % 2 === 0) // Step 1: Keep only even numbers
.map(num => num * 2) // Step 2: Double each even number
.reduce((sum, num) => sum + num, 0); // Step 3: Sum them all up
console.log(result); // Output: 60
Some examples are given below
// Example 1 — Extracting Names of Active Users
let users = [
{ name: "Alice", age: 25, isActive: true },
{ name: "Bob", age: 45, isActive: false },
{ name: "Charlie", age: 35, isActive: true },
{ name: "David", age: 50, isActive: false }
];
let activeUserNames = users
.filter(user => user.isActive) // Keep only active users
.map(user => user.name); // Extract their names
console.log(activeUserNames); // ["Alice", "Charlie"]
// Example 2 — Find Average Age of Students who Passed
let students = [
{ name: "John", age: 18, score: 85 },
{ name: "Sarah", age: 19, score: 45 },
{ name: "Mike", age: 20, score: 70 },
{ name: "Emma", age: 21, score: 90 }
];
let averageAge = students
.filter(student => student.score >= 50) // Only those who passed
.map(student => student.age) // Extract ages
.reduce((sum, age, _, arr) => sum + age / arr.length, 0); // Average age calculation
console.log(averageAge); // Average age of passed students
Additional Resources — Level Up Your Learning
Official Documentation
Recommended YouTube Tutorials
Comments
Join the discussionNo comments yet. Be the first to comment.