CodeBlanks Logo Icon CodeBlanks

Summary - Array methods

Combine map, filter and reduce to write a sales report.

Summary - Array methods

In this group you learned five array methods. map transforms each element, filter keeps the matching ones, reduce folds to a single value, find returns the first match, and forEach walks each element for side effects.

You can chain them: prices.filter(p => p > 100).map(p => p * 1.1) first keeps the expensive ones, then adds tax. Chaining is a powerful way to process data step by step.

In the final task you will build a sales report: filter sales above 100, apply a 10% commission to each, then sum the commissions. You will use all three methods together.

Practice Sales report

Define an array of sales [80, 150, 200, 60]. Use filter to keep sales above 100, map to compute the 10% commission of each (sale * 10 / 100), then reduce to sum the commissions (initial 0). Print the total with console.log. You can chain the calls.

Starter code

index.js
const sales = [80, 150, 200, 60];
// Filter above 100, apply 10% commission, sum and print

Sample solution

index.js
const sales = [80, 150, 200, 60];
const total = sales.filter(s => s > 100).map(s => s * 10 / 100).reduce((sum, c) => sum + c, 0);
console.log(total);

Expected output

35

Practice Total and average

Define an array of scores [40, 60, 80, 20]. Use reduce to compute the sum (initial 0) and print it with console.log. Then compute the average by dividing by the number of scores and print that too.

Starter code

index.js
const scores = [40, 60, 80, 20];
// Compute the total and the average, print both

Sample solution

index.js
const scores = [40, 60, 80, 20];
const total = scores.reduce((sum, s) => sum + s, 0);
console.log(total);
const avg = total / scores.length;
console.log(avg);

Expected output

200
50

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each method to its purpose

Term Meaning
map Transform
filter Filter
reduce Fold to one value
find First match
forEach Side effect

2 Which chain is correct?

  • reduce().map().filter()
  • map().reduce().filter()
  • forEach().map().filter()
  • filter().map().reduce() Correct answer

Explanation: first filter, then map, finally reduce.

3 Chained call

Question
const nums = [1, 2, 3, 4];
const result = nums.filter(n => n > 1).____(n => n * 2);
Answer
const nums = [1, 2, 3, 4];
const result = nums.filter(n => n > 1).map(n => n * 2);

Explanation: map doubles each remaining element.

All lessons in Beginner