We use cookies to enhance your experience on the site
CodeWorlds

Higher-Order Functions: map, filter, reduce

In the laboratories of Jurassic Park, scientists process enormous amounts of dinosaur data every day - filtering DNA samples, transforming analysis results, and aggregating statistics. Higher-order functions are tools that let you do the same with data in JavaScript - elegantly, readably, and safely.

What is a Higher-Order Function?

A higher-order function is a function that takes another function as an argument or returns a function as a result. It's like a machine in the laboratory that accepts an instruction (function) and applies it to each DNA sample.

Array.map() - Data Transformation

map
creates a new array by applying a given function to each element. The original array remains untouched.

1const specimens = [
2  { name: 'Rex', weight: 8000, age: 5 },
3  { name: 'Blue', weight: 150, age: 3 },
4  { name: 'Brachio', weight: 56000, age: 12 },
5];
6
7// Transformation - extracting just the names
8const names = specimens.map((dino) => dino.name);
9// ['Rex', 'Blue', 'Brachio']
10
11// Transformation - computing a report
12const reports = specimens.map((dino) => ({
13  label: dino.name.toUpperCase(),
14  weightInTons: dino.weight / 1000,
15  category: dino.weight > 5000 ? 'large' : 'small',
16}));
17// [{ label: 'REX', weightInTons: 8, category: 'large' }, ...]

Array.filter() - Data Selection

filter
creates a new array with elements that satisfy a condition (predicate). It's like filtering DNA samples - you keep only those that pass quality control.

1const allDinosaurs = [
2  { name: 'Rex', diet: 'carnivore', health: 95 },
3  { name: 'Brachio', diet: 'herbivore', health: 88 },
4  { name: 'Raptor', diet: 'carnivore', health: 42 },
5  { name: 'Stego', diet: 'herbivore', health: 100 },
6];
7
8// Filtering - only healthy dinosaurs
9const healthy = allDinosaurs.filter((dino) => dino.health > 80);
10// [Rex, Brachio, Stego]
11
12// Filtering - predators needing help
13const sickCarnivores = allDinosaurs.filter(
14  (dino) => dino.diet === 'carnivore' && dino.health < 50
15);
16// [Raptor]

Array.reduce() - Data Aggregation

reduce
processes an array into a single value, accumulating the result element by element. It's like a summary report - it gathers data from all enclosures and creates one summary.

1const parkData = [
2  { zone: 'A', dinosaurs: 5, incidents: 0 },
3  { zone: 'B', dinosaurs: 3, incidents: 2 },
4  { zone: 'C', dinosaurs: 8, incidents: 1 },
5];
6
7// Sum of all dinosaurs
8const totalDinos = parkData.reduce(
9  (sum, zone) => sum + zone.dinosaurs, 0
10);
11// 16
12
13// Grouping zones by safety
14const grouped = parkData.reduce((groups, zone) => {
15  const key = zone.incidents === 0 ? 'safe' : 'risky';
16  return { ...groups, [key]: [...(groups[key] || []), zone.zone] };
17}, {});
18// { safe: ['A'], risky: ['B', 'C'] }

Chaining map, filter, and reduce

The true power of FP reveals itself when you chain these functions into a processing pipeline:

1const specimens = [
2  { id: 'S001', species: 'T-Rex', viability: 0.95, cost: 50000 },
3  { id: 'S002', species: 'Raptor', viability: 0.3, cost: 20000 },
4  { id: 'S003', species: 'Brachio', viability: 0.88, cost: 80000 },
5  { id: 'S004', species: 'Stego', viability: 0.72, cost: 35000 },
6  { id: 'S005', species: 'Raptor', viability: 0.91, cost: 22000 },
7];
8
9// Pipeline: filter viability > 0.7 -> calculate cost -> sum
10const totalViableCost = specimens
11  .filter((s) => s.viability > 0.7)
12  .map((s) => s.cost * s.viability)
13  .reduce((total, cost) => total + cost, 0);
14// 47500 + 70400 + 25200 + 20020 = 163120
Go to CodeWorlds