Introductions
JavaScript array methods like map(), filter(), reduce(), and forEach() make it easier to work with lists of data. These methods are used frequently in real-world JavaScript applications. In this chapter, you will practice each method with simple examples and gradually combine them to solve practical problems. JavaScript map() and filter() Practice Questions with Solutions help to build concepts.
Question 1: Display Array Elements Using forEach()
Problem
Create an array of five numbers and use forEach() to display each number.
Solution
let numbers = [10, 20, 30, 40, 50];
numbers.forEach(function(number) {
console.log(number);
});
Output
10
20
30
40
50
Step-by-step Explanation
- The
numbersarray contains five values. forEach()runs a function for every element.- The current element is stored in
number. console.log()displays the current number.- The process repeats until every element has been displayed.
Question 2: Double Every Number Using map()
Problem
Create an array of numbers and use map() to create a new array containing double each number.
Solution
let numbers = [2, 4, 6, 8];
let doubled = numbers.map(function(number) {
return number * 2;
});
console.log(doubled);
Output
[4, 8, 12, 16]
Step-by-step Explanation
map()processes every element in the array.- The callback receives one number at a time.
- Each number is multiplied by
2. - The returned values are collected into a new array.
- The original
numbersarray is not changed.
Question 3: Find Even Numbers Using filter()
Problem
Create an array of numbers and use filter() to create a new array containing only even numbers.
Solution
let numbers = [1, 2, 3, 4, 5, 6];
let evenNumbers = numbers.filter(function(number) {
return number % 2 === 0;
});
console.log(evenNumbers);
Output
[2, 4, 6]
Step-by-step Explanation
filter()checks every element.% 2checks whether the number is divisible by2.- Even numbers produce a remainder of
0. - If the condition is
true, the number is included. - The new array contains
2,4, and6.
Question 4: Calculate the Total Using reduce()
Problem
Create an array of numbers and use reduce() to calculate their total.
Solution
let numbers = [10, 20, 30, 40];
let total = numbers.reduce(function(sum, number) {
return sum + number;
}, 0);
console.log(total);
Output
100
Step-by-step Explanation
reduce() combines all array elements into a single value.
The calculation happens like this:
0 + 10 = 10
10 + 20 = 30
30 + 30 = 60
60 + 40 = 100
sumstores the accumulated value.numberrepresents the current array element.0is the initial value.- Each number is added to
sum. - The final result is
100.
Question 5: Convert Names to Uppercase Using map()
Problem
Create an array of names and use map() to convert every name to uppercase.
Solution
let names = ["rahul", "priya", "aman", "neha"];
let upperNames = names.map(function(name) {
return name.toUpperCase();
});
console.log(upperNames);
Output
["RAHUL", "PRIYA", "AMAN", "NEHA"]
Step-by-step Explanation
- The
namesarray contains four names. map()processes each name.toUpperCase()converts each name to uppercase.- The returned values form a new array.
- The original array remains unchanged.
Question 6: Find Numbers Greater Than 50 Using filter()
Problem
Create an array of marks and find all marks greater than 50.
Solution
let marks = [35, 75, 45, 90, 60, 40];
let passedMarks = marks.filter(function(mark) {
return mark > 50;
});
console.log(passedMarks);
Output
[75, 90, 60]
Step-by-step Explanation
filter()checks every mark.- The condition is
mark > 50. 35is rejected.75is accepted.45is rejected.90is accepted.60is accepted.40is rejected.- The final array is
[75, 90, 60].
Question 7: Calculate Shopping Cart Total Using reduce()
Problem
Create an array containing product prices and calculate the total shopping cost.
Solution
let prices = [500, 250, 100, 150];
let total = prices.reduce(function(sum, price) {
return sum + price;
}, 0);
console.log(total);
Output
1000
Step-by-step Explanation
The calculation is:
0 + 500 = 500
500 + 250 = 750
750 + 100 = 850
850 + 150 = 1000
reduce()starts with0.- It adds the first price.
- The result becomes the new accumulated value.
- The process continues with every price.
- The final shopping total is
1000.
Question 8: Use forEach() to Calculate a Total
Problem
Create an array of expenses and use forEach() to calculate their total.
Solution
let expenses = [100, 200, 150, 50];
let total = 0;
expenses.forEach(function(expense) {
total = total + expense;
});
console.log(total);
Output
500
Step-by-step Explanation
totalstarts at0.forEach()visits every expense.- Each expense is added to
total. - The calculations are:
0 + 100 = 100
100 + 200 = 300
300 + 150 = 450
450 + 50 = 500
- The final total is
500.
forEach() can perform this task, but reduce() is often more natural when the goal is to produce one final value.
Question 9: Combine filter() and map()
Problem
Create an array of numbers. First find numbers greater than 10, then create a new array containing their doubles.
Solution
let numbers = [5, 12, 8, 20, 15];
let result = numbers
.filter(number => number > 10)
.map(number => number * 2);
console.log(result);
Output
[24, 40, 30]
Step-by-step Explanation
First, filter() selects numbers greater than 10:
[12, 20, 15]
Then map() doubles each selected number:
12 × 2 = 24
20 × 2 = 40
15 × 2 = 30
The final result is:
[24, 40, 30]
This shows how multiple array methods can be chained together.
Question 10: Calculate Total Price from Objects Using reduce()
Problem
Create an array of products containing name, price, and quantity. Use reduce() to calculate the total cost of all products.
Solution
let products = [
{ name: "Book", price: 200, quantity: 2 },
{ name: "Pen", price: 20, quantity: 5 },
{ name: "Bag", price: 500, quantity: 1 }
];
let total = products.reduce(function(sum, product) {
return sum + (product.price * product.quantity);
}, 0);
console.log(total);
Output
1000
Step-by-step Explanation
For the first product:
200 × 2 = 400
For the second product:
20 × 5 = 100
For the third product:
500 × 1 = 500
Now add them:
400 + 100 + 500 = 1000
reduce()starts with0.productrepresents the current object.product.pricegets the product price.product.quantitygets the quantity.- Price and quantity are multiplied.
- The result is added to
sum. - After all products are processed, the final total is
1000.
Key Takeaways
forEach()runs a function for every array element.map()creates a new array by transforming elements.filter()creates a new array containing elements that satisfy a condition.reduce()combines array elements into one final value.forEach()does not normally return a new array.map()is useful when you want to transform data.filter()is useful when you want to select data.reduce()is useful for totals, calculations, and accumulating values.- These methods can be combined using method chaining.
- Arrow functions make these methods shorter and easier to read.
- These methods are widely used when working with real-world JavaScript data.
FAQs
1. What is the difference between map() and forEach()?
map() creates and returns a new array, while forEach() is generally used to perform an action for each element.
let doubled = numbers.map(number => number * 2);
With forEach():
numbers.forEach(number => {
console.log(number);
});
2. What is filter() used for?
filter() is used to create a new array containing elements that satisfy a condition.
let numbers = [5, 10, 15, 20];
let result = numbers.filter(number => number > 10);
Output:
[15, 20]
3. What is reduce() used for?
reduce() is commonly used when you want to combine array values into a single result.
For example, calculating a total:
let total = numbers.reduce((sum, number) => sum + number, 0);
4. Does map() change the original array?
Normally, map() creates a new array and does not change the original array.
let numbers = [1, 2, 3];
let doubled = numbers.map(number => number * 2);
The original numbers array remains [1, 2, 3].
5. Does filter() change the original array?
No. filter() returns a new array containing the elements that pass the condition.
6. What is the initial value in reduce()?
The initial value is the starting value for the accumulator.
let total = numbers.reduce((sum, number) => {
return sum + number;
}, 0);
Here, 0 is the initial value.
7. Can map(), filter(), and reduce() be chained together?
Yes. You can use one method after another.
let result = numbers
.filter(number => number > 10)
.map(number => number * 2);
The output of filter() becomes the input for map().
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
