JavaScript and TypeScript course · Module 2: Functions, Arrays and Objects
Array Iteration (forEach, map, filter, reduce)
In this lesson9
In our Jurassic Park we collect a mountain of data about the dinosaurs - their species, measurements, feeding habits, aggression levels and much more. Once all of that lands in an array, we hardly ever care about a single entry: we want to visit every element, reshape them, pull out the ones that matter, or boil the whole herd down to one number for the control room. JavaScript ships a family of array iteration methods built for exactly that, and each of them has a job of its own.
The forEach Method
The forEach method runs a function once for every element of an array. It is the most basic way of iterating - we reach for it when we want to do something with each element, such as printing it or sending it to the monitoring station, and we do not need a new array in return.
// An array of objects representing the dinosaurs in our park
const dinosaurs = [
{ name: "Tyrannosaurus", diet: "carnivore", aggressionLevel: 10 },
{ name: "Triceratops", diet: "herbivore", aggressionLevel: 4 },
{ name: "Velociraptor", diet: "carnivore", aggressionLevel: 9 },
{ name: "Stegosaurus", diet: "herbivore", aggressionLevel: 2 },
{ name: "Brachiosaurus", diet: "herbivore", aggressionLevel: 1 }
];
// We use forEach to print the names of all the dinosaurs
console.log("List of dinosaurs in the park:");
dinosaurs.forEach(function(dino) {
console.log(dino.name);
});
// We can also use an arrow function for a more concise notation
console.log("List of dinosaurs with their aggression level:");
dinosaurs.forEach(dino => {
console.log(`${dino.name}: Aggression level ${dino.aggressionLevel}/10`);
});The forEach method hands nothing back - to be exact, it returns undefined - so we use it when we only want to perform an action on the elements, without building a new array. It is worth knowing what it cannot do either: you cannot stop it halfway through. A return inside the callback ends that one call and the walk moves straight on to the next dinosaur, and break is not even allowed in there. When you need to bail out early, that is a job for find, some, every or a classic for loop.
The map Method
The map method creates a new array containing the results of calling a provided function on every element of the original array. It is remarkably useful whenever we need to convert data from one shape into another - turning full dinosaur records into a plain list of names, or into short safety summaries the wardens can actually read.
// We use map to build a new array containing only the dinosaur names
const dinoNames = dinosaurs.map(dino => dino.name);
console.log("Dinosaur names:", dinoNames);
// Result: ["Tyrannosaurus", "Triceratops", "Velociraptor", "Stegosaurus", "Brachiosaurus"]
// We can also build more complex transformations
const dinoSummaries = dinosaurs.map(dino => {
return {
name: dino.name,
dangerLevel: dino.diet === "carnivore" ? "High" : "Low",
warning: dino.aggressionLevel > 7 ? "Handle with extreme caution!" : "Standard safety procedures"
};
});
console.log("Dinosaur safety summary:", dinoSummaries);Unlike forEach, the map method always returns a new array of the same length as the original, holding the transformed elements. That is exactly the key difference between the two: map() returns a new array, while forEach() returns undefined. It is not a question of speed - map() is not faster, both methods visit every element exactly once - and they certainly do not work identically. Neither of them can be stopped mid-run, so that is no difference between them either. Reach for map when you want the result, and for forEach when you only care about the side effect.
The filter Method
The filter method creates a new array containing only the elements that satisfy a given condition. It is the perfect tool when we need to pull a subset out of a bigger collection - every carnivore, every animal due for a health check, every enclosure in the eastern sector.
// We filter to get only the carnivorous dinosaurs
const carnivores = dinosaurs.filter(dino => dino.diet === "carnivore");
console.log("Carnivorous dinosaurs:", carnivores);
// We can combine conditions to build more complex filters
const dangerousDinos = dinosaurs.filter(dino => {
return dino.diet === "carnivore" && dino.aggressionLevel > 7;
});
console.log("The most dangerous dinosaurs:", dangerousDinos);
// We can also combine filter with map, to narrow down first and transform afterwards
const safetyWarnings = dinosaurs
.filter(dino => dino.aggressionLevel > 5)
.map(dino => `WARNING: ${dino.name} has a high aggression level!`);
console.log("Safety warnings:", safetyWarnings);The filter method returns a new array which may be shorter than the original, holding only the elements that made it through the "filter" - the ones for which the test function returned true. Notice that the dinosaurs array itself is left completely untouched: just like map, filter never edits the collection it was called on, it only reports on it.
The reduce Method
The reduce method is the most powerful of the iteration methods, and also the most involved. It lets us "reduce" an array to a single value by running a function over every element while carrying the result of the previous step along with us.
// We calculate the sum of the aggression levels of all the dinosaurs
const totalAggressionLevel = dinosaurs.reduce((total, dino) => {
return total + dino.aggressionLevel;
}, 0); // 0 is the initial value
console.log("Total aggression level in the park:", totalAggressionLevel);
// We can use reduce to build richer structures, such as an object grouping dinosaurs by diet
const dinosByDiet = dinosaurs.reduce((groups, dino) => {
// If the group for this diet does not exist yet, we create it
if (!groups[dino.diet]) {
groups[dino.diet] = [];
}
// We add the dinosaur to the matching group
groups[dino.diet].push(dino.name);
return groups;
}, {}); // {} is the initial value (an empty object)
console.log("Dinosaurs grouped by diet:", dinosByDiet);
// Result: { "carnivore": ["Tyrannosaurus", "Velociraptor"], "herbivore": ["Triceratops", "Stegosaurus", "Brachiosaurus"] }So what is the reduce() method on an array used for? It reduces an array to a single value - a sum, an average, the heaviest specimen, or one grouped object like the one above. The name misleads a lot of people, so let us be precise about what it does not do: it does not remove elements from an array, it does not reduce the size of the array (our dinosaurs array still holds five records afterwards), and it has nothing to do with sorting in descending order - that job belongs to sort.
The reduce method takes two parameters:
- A reducer function, which itself takes at least two parameters:
- The accumulator: the value returned from the previous iteration (or the initial value)
- The current element: the element of the array being processed right now
- An initial value (optional, but strongly recommended)
The find Method
The find method returns the first element of an array that satisfies a given condition. When the park systems need one specific record rather than a whole list, this is the method to reach for.
// We look for a dinosaur with a given name
const stegosaurus = dinosaurs.find(dino => dino.name === "Stegosaurus");
console.log("Stegosaurus information:", stegosaurus);
// We look for the first carnivore with an aggression level above 8
const dangerousCarnivore = dinosaurs.find(dino => {
return dino.diet === "carnivore" && dino.aggressionLevel > 8;
});
console.log("First dangerous carnivore:", dangerousCarnivore); // TyrannosaurusUnlike filter, which returns an array of every matching element, find returns only the first match, and when nothing matches it returns undefined. It also stops the moment it gets a hit, so the remaining dinosaurs are never examined. Its close twin findIndex behaves the same way but gives you the position of that first match instead of the element itself, and returns -1 when there is no match at all.
The some and every Methods
The some and every methods return a boolean value and are useful for checking whether the elements of an array meet certain criteria. Neither of them builds a new array - they answer a yes-or-no question about the whole collection.
some
The some method checks whether at least one element of the array satisfies the given condition.
// We check whether there are any dangerous dinosaurs in the park
const hasHighAggressionDinos = dinosaurs.some(dino => dino.aggressionLevel > 8);
console.log("Does the park have high aggression dinosaurs?", hasHighAggressionDinos); // true
// We check whether there are any omnivorous dinosaurs in the park
const hasOmnivores = dinosaurs.some(dino => dino.diet === "omnivore");
console.log("Does the park have omnivorous dinosaurs?", hasOmnivores); // falseThe some method short-circuits: it stops as soon as it finds the first element that passes the test, because it already knows the answer is true and looking at the rest of the herd would change nothing.
every
The every method checks whether all the elements of the array satisfy the given condition.
// We check whether every dinosaur has an aggression level assigned
const allHaveAggressionLevel = dinosaurs.every(dino => dino.aggressionLevel !== undefined);
console.log("Do all the dinosaurs have an aggression level?", allHaveAggressionLevel); // true
// We check whether all the dinosaurs are herbivores
const allHerbivores = dinosaurs.every(dino => dino.diet === "herbivore");
console.log("Are all the dinosaurs herbivores?", allHerbivores); // falseThe every method short-circuits the other way round: it stops at the first element that fails the test, because a single counterexample is enough to answer false. Read out loud, the pair sounds almost like plain English - "is there some dangerous dinosaur?" and "is every dinosaur fed?".
The sort Method
The sort method orders the elements of an array and returns the sorted array. By default it compares elements as strings, which can lead to unexpected results when sorting numbers - by default [10, 9, 100] comes out as [10, 100, 9]. That is why we usually pass it a comparison function.
// We sort the dinosaurs by name (alphabetically)
const dinosSortedByName = [...dinosaurs].sort((a, b) => {
return a.name.localeCompare(b.name);
});
console.log("Dinosaurs sorted alphabetically:", dinosSortedByName);
// We sort the dinosaurs by aggression level (from the least to the most aggressive)
const dinosSortedByAggression = [...dinosaurs].sort((a, b) => {
return a.aggressionLevel - b.aggressionLevel;
});
console.log("Dinosaurs sorted by aggression (ascending):", dinosSortedByAggression);
// We sort the dinosaurs by aggression level (from the most to the least aggressive)
const mostDangerousFirst = [...dinosaurs].sort((a, b) => {
return b.aggressionLevel - a.aggressionLevel;
});
console.log("Dinosaurs sorted by aggression (descending):", mostDangerousFirst);Notice that we use the spread operator (...) to create a copy of the array before sorting, because sort modifies the original array and we want to preserve the original order. The comparison function decides the direction: a negative result puts a first, which is why a.aggressionLevel - b.aggressionLevel sorts ascending, and flipping the two operands sorts descending.
Combining Methods (Chaining)
One of the most powerful features of these methods is that we can join them into "chains" and carry out complex operations on our data in a single readable expression. It works because filter, map and sort all give back an array, so the next method can be called straight on the result.
// Let us find the names of all the herbivorous dinosaurs, sorted alphabetically
const sortedHerbivoreNames = dinosaurs
.filter(dino => dino.diet === "herbivore") // First we filter
.map(dino => dino.name) // Then we transform into an array of names
.sort(); // Finally we sort alphabetically
console.log("Herbivores (alphabetically):", sortedHerbivoreNames);
// Result: ["Brachiosaurus", "Stegosaurus", "Triceratops"]
// Let us calculate the average aggression level of the carnivores
const averageCarnivoreAggression = dinosaurs
.filter(dino => dino.diet === "carnivore") // First we keep only the carnivores
.reduce((sum, dino, index, array) => { // Then we reduce it down to an average
sum += dino.aggressionLevel; // We add the aggression level to the sum
// If this is the last element, we divide by the number of elements
if (index === array.length - 1) {
return sum / array.length;
}
return sum; // We return the partial sum
}, 0);
console.log("Average carnivore aggression level:", averageCarnivoreAggression); // 9.5Read a chain from left to right and the order of its links is always the same: the array comes first, then the method that narrows it down, then the method that transforms whatever survived. The array is the receiver, so dinosaurs always opens the chain, then comes .filter(...), and only then .map(...).
// If every record carried a ready dangerous flag, the chain would read like a sentence
const dangerousNames = dinosaurs
.filter(d => d.dangerous)
.map(d => d.name);
// Our records store a diet string instead, so the test is a little longer -
// but the order of the links in the chain never changes
const carnivoreNames = dinosaurs
.filter(d => d.diet === "carnivore")
.map(d => d.name);
console.log("Carnivore names:", carnivoreNames);Swapping those two links around would break everything: after .map(d => d.name) we are holding an array of plain strings, and a string has no dangerous property left to filter on. Filter first, map second - that is the order worth memorising.
Summary
The array iteration methods in JavaScript are an invaluable tool when working with collections of data. Each of them has its own speciality:
- forEach: when we want to perform an operation on every element, without creating a new array
- map: when we want to transform every element of the array into something else
- filter: when we want to select the subgroup of elements that meet given criteria
- reduce: when we want to "reduce" the array to a single value or a new structure
- find: when we are looking for the first element that meets a given criterion
- some/every: when we want to check whether some/all elements meet a given criterion
- sort: when we want to put the elements of the array in order
In our Jurassic Park these methods are indispensable for managing dinosaur data efficiently, monitoring safety and making decisions based on data. As Dr. Rex puts it, iteration methods are the park's morning briefing: forEach walks the daily checklist, filter picks out only the animals that need attention, map turns them into a report, and reduce gives the control room a single number to act on.
Code for this lesson: index.js
// Iterating over arrays - Jurassic Park
console.log("Advanced Iterations");
console.log("forEach, map, filter, reduce\n");
// ===========================================
// TEST DATA
// ===========================================
const dinosaurs = [
{ id: 1, name: "Rexy", species: "T-Rex", age: 8, weight: 8000, sector: "A", health: 95, carnivore: true, fed: true },
{ id: 2, name: "Blue", species: "Velociraptor", age: 5, weight: 80, sector: "B", health: 100, carnivore: true, fed: false },
{ id: 3, name: "Charlie", species: "Velociraptor", age: 5, weight: 80, sector: "B", health: 85, carnivore: true, fed: false },
{ id: 4, name: "Delta", species: "Velociraptor", age: 5, weight: 80, sector: "B", health: 45, carnivore: true, fed: true },
{ id: 5, name: "Trike", species: "Triceratops", age: 7, weight: 9000, sector: "C", health: 70, carnivore: false, fed: true },
{ id: 6, name: "Stego", species: "Stegosaurus", age: 6, weight: 5000, sector: "C", health: 92, carnivore: false, fed: false },
{ id: 7, name: "Brachio", species: "Brachiosaurus", age: 10, weight: 50000, sector: "D", health: 88, carnivore: false, fed: true }
];
// ===========================================
// 1. forEach() - CLASSIC ITERATION
// ===========================================
console.log("=== 1. forEach() - Iteration without a return value ===");
console.log("\nList of all dinosaurs:");
dinosaurs.forEach((dino, index) => {
const icon = dino.carnivore ? "carnivore" : "herbivore";
console.log(` ${index + 1}. ${icon} ${dino.name} (${dino.species})`);
});
// forEach with side effects
let totalWeight = 0;
dinosaurs.forEach(dino => {
totalWeight += dino.weight;
});
console.log(`\nTotal weight: ${totalWeight}kg`);
// ===========================================
// 2. map() - DATA TRANSFORMATION
// ===========================================
console.log("\n=== 2. map() - Transformation of each element ===");
// Example 1: Simple value extraction
const names = dinosaurs.map(dino => dino.name);
console.log("\nNames only:", names.join(", "));
// Example 2: Creating new objects
const summaries = dinosaurs.map(dino => ({
name: dino.name,
type: dino.carnivore ? "Carnivore" : "Herbivore",
status: dino.health >= 80 ? "Healthy" : "Needs attention"
}));
console.log("\nSummaries:");
summaries.forEach(s => {
console.log(` ${s.name}: ${s.type}, Status: ${s.status}`);
});
// Example 3: Calculations
const healthPercentages = dinosaurs.map(dino => {
const healthStatus = dino.health >= 90 ? "*" : dino.health >= 70 ? "OK" : "!";
return `${healthStatus} ${dino.name}: ${dino.health}%`;
});
console.log("\nHealth levels:");
healthPercentages.forEach(h => console.log(` ${h}`));
// ===========================================
// 3. filter() - FILTERING
// ===========================================
console.log("\n=== 3. filter() - Selecting elements ===");
// Example 1: One condition
const carnivores = dinosaurs.filter(dino => dino.carnivore);
console.log(`\nCarnivores (${carnivores.length}):`, carnivores.map(d => d.name).join(", "));
// Example 2: Multiple conditions
const healthyCarnivores = dinosaurs.filter(dino =>
dino.carnivore && dino.health >= 80
);
console.log(`Healthy carnivores (${healthyCarnivores.length}):`, healthyCarnivores.map(d => d.name).join(", "));
// Example 3: Complex conditions
const needsAttention = dinosaurs.filter(dino =>
dino.health < 80 || !dino.fed
);
console.log(`\nNeed attention (${needsAttention.length}):`);
needsAttention.forEach(dino => {
const reasons = [];
if (dino.health < 80) reasons.push(`health: ${dino.health}%`);
if (!dino.fed) reasons.push("hungry");
console.log(` ${dino.name}: ${reasons.join(", ")}`);
});
// Example 4: Filtering by sector
const sectorB = dinosaurs.filter(dino => dino.sector === "B");
console.log(`\nSector B (${sectorB.length}):`, sectorB.map(d => d.name).join(", "));
// ===========================================
// 4. reduce() - AGGREGATION
// ===========================================
console.log("\n=== 4. reduce() - Data aggregation ===");
// Example 1: Sum
const totalHealthPoints = dinosaurs.reduce((sum, dino) => sum + dino.health, 0);
console.log(`\nSum of health points: ${totalHealthPoints}`);
// Example 2: Average
const avgHealth = totalHealthPoints / dinosaurs.length;
console.log(`Average health: ${avgHealth.toFixed(1)}%`);
// Example 3: Finding max/min
const oldest = dinosaurs.reduce((max, dino) =>
dino.age > max.age ? dino : max
);
console.log(`\nOldest: ${oldest.name} (${oldest.age} years)`);
const youngest = dinosaurs.reduce((min, dino) =>
dino.age < min.age ? dino : min
);
console.log(`Youngest: ${youngest.name} (${youngest.age} years)`);
// Example 4: Grouping
const bySector = dinosaurs.reduce((acc, dino) => {
if (!acc[dino.sector]) acc[dino.sector] = [];
acc[dino.sector].push(dino.name);
return acc;
}, {});
console.log("\nGrouping by sector:");
Object.entries(bySector).sort().forEach(([sector, dinos]) => {
console.log(` Sector ${sector}: ${dinos.join(", ")}`);
});
// Example 5: Counting occurrences
const speciesCount = dinosaurs.reduce((acc, dino) => {
acc[dino.species] = (acc[dino.species] || 0) + 1;
return acc;
}, {});
console.log("\nCount by species:");
Object.entries(speciesCount).forEach(([species, count]) => {
console.log(` ${species}: ${count}`);
});
// Example 6: Building a statistics object
const stats = dinosaurs.reduce((acc, dino) => {
acc.totalDinos++;
acc.totalWeight += dino.weight;
acc.totalAge += dino.age;
if (dino.carnivore) acc.carnivores++;
if (dino.health >= 90) acc.veryHealthy++;
return acc;
}, { totalDinos: 0, totalWeight: 0, totalAge: 0, carnivores: 0, veryHealthy: 0 });
console.log("\nSummary statistics:");
console.log(` Total dinosaurs: ${stats.totalDinos}`);
console.log(` Total weight: ${stats.totalWeight}kg`);
console.log(` Average age: ${(stats.totalAge / stats.totalDinos).toFixed(1)} years`);
console.log(` Carnivores: ${stats.carnivores}`);
console.log(` Very healthy (≥90%): ${stats.veryHealthy}`);
// ===========================================
// 5. CHAINING METHODS
// ===========================================
console.log("\n=== 5. Method chaining ===");
// Example 1: filter + map + sort
const topHealthyCarnivores = dinosaurs
.filter(d => d.carnivore)
.filter(d => d.health >= 80)
.map(d => ({ name: d.name, health: d.health }))
.sort((a, b) => b.health - a.health)
.slice(0, 3);
console.log("\nTOP 3 healthy carnivores:");
topHealthyCarnivores.forEach((d, i) => {
console.log(` ${i + 1}. ${d.name} - ${d.health}%`);
});
// Example 2: filter + map + reduce
const heavyHerbivoreWeight = dinosaurs
.filter(d => !d.carnivore)
.filter(d => d.weight > 1000)
.map(d => d.weight)
.reduce((sum, weight) => sum + weight, 0);
console.log(`\nTotal weight of heavy herbivores: ${heavyHerbivoreWeight}kg`);
// Example 3: Complex processing
const sectorReport = Object.entries(
dinosaurs
.filter(d => d.health >= 70)
.reduce((acc, d) => {
if (!acc[d.sector]) {
acc[d.sector] = { count: 0, avgHealth: 0, totalHealth: 0 };
}
acc[d.sector].count++;
acc[d.sector].totalHealth += d.health;
return acc;
}, {})
)
.map(([sector, data]) => ({
sector,
count: data.count,
avgHealth: (data.totalHealth / data.count).toFixed(1)
}))
.sort((a, b) => b.avgHealth - a.avgHealth);
console.log("\nSector report (health ≥70%):");
sectorReport.forEach(s => {
console.log(` Sector ${s.sector}: ${s.count} dinosaurs, average health: ${s.avgHealth}%`);
});
// ===========================================
// 6. COMPARING APPROACHES
// ===========================================
console.log("\n=== 6. Comparing approaches ===");
console.log("\nTask: Find the names of carnivores in sector B");
// Way 1: for loop (imperative)
const result1 = [];
for (let i = 0; i < dinosaurs.length; i++) {
if (dinosaurs[i].carnivore && dinosaurs[i].sector === "B") {
result1.push(dinosaurs[i].name);
}
}
console.log("For loop:", result1);
// Way 2: forEach (partly functional)
const result2 = [];
dinosaurs.forEach(dino => {
if (dino.carnivore && dino.sector === "B") {
result2.push(dino.name);
}
});
console.log("forEach:", result2);
// Way 3: filter + map (functional)
const result3 = dinosaurs
.filter(d => d.carnivore && d.sector === "B")
.map(d => d.name);
console.log("filter + map:", result3);
// ===========================================
// 7. COMPLEX EXAMPLE
// ===========================================
console.log("\n=== 7. Reporting system - complex example ===");
class ParkReportingSystem {
constructor(dinosaurs) {
this.dinosaurs = dinosaurs;
}
// Main dashboard
getDashboard() {
const total = this.dinosaurs.length;
const healthStats = this.dinosaurs.reduce((acc, d) => {
if (d.health >= 90) acc.excellent++;
else if (d.health >= 70) acc.good++;
else acc.poor++;
acc.total += d.health;
return acc;
}, { excellent: 0, good: 0, poor: 0, total: 0 });
const feedingStats = this.dinosaurs.reduce((acc, d) => {
if (d.fed) acc.fed++;
else acc.hungry++;
return acc;
}, { fed: 0, hungry: 0 });
return {
totalDinosaurs: total,
avgHealth: (healthStats.total / total).toFixed(1),
healthBreakdown: {
excellent: healthStats.excellent,
good: healthStats.good,
poor: healthStats.poor
},
feeding: feedingStats
};
}
// Critical alerts
getCriticalAlerts() {
return this.dinosaurs
.filter(d => d.health < 50 || (d.carnivore && !d.fed))
.map(d => ({
name: d.name,
sector: d.sector,
issue: d.health < 50 ? `Critical health: ${d.health}%` : "Hungry carnivore!",
priority: d.health < 50 && d.carnivore && !d.fed ? "EXTREME" : "HIGH"
}))
.sort((a, b) => {
const priorityOrder = { "EXTREME": 0, "HIGH": 1 };
return priorityOrder[a.priority] - priorityOrder[b.priority];
});
}
// Health ranking
getHealthRanking(limit = 5) {
return this.dinosaurs
.map(d => ({
name: d.name,
species: d.species,
health: d.health,
sector: d.sector
}))
.sort((a, b) => b.health - a.health)
.slice(0, limit);
}
// Sector analysis
getSectorAnalysis() {
const sectorData = this.dinosaurs.reduce((acc, d) => {
if (!acc[d.sector]) {
acc[d.sector] = {
dinosaurs: [],
totalHealth: 0,
carnivores: 0,
unfed: 0
};
}
acc[d.sector].dinosaurs.push(d.name);
acc[d.sector].totalHealth += d.health;
if (d.carnivore) acc[d.sector].carnivores++;
if (!d.fed) acc[d.sector].unfed++;
return acc;
}, {});
return Object.entries(sectorData)
.map(([sector, data]) => ({
sector,
count: data.dinosaurs.length,
avgHealth: (data.totalHealth / data.dinosaurs.length).toFixed(1),
carnivores: data.carnivores,
unfed: data.unfed,
dinosaurs: data.dinosaurs
}))
.sort((a, b) => a.sector.localeCompare(b.sector));
}
// Display full report
displayFullReport() {
console.log("\n" + "=".repeat(70));
console.log("JURASSIC PARK - COMPREHENSIVE REPORT");
console.log("=".repeat(70));
// Dashboard
const dashboard = this.getDashboard();
console.log("\nDASHBOARD");
console.log(` Total dinosaurs: ${dashboard.totalDinosaurs}`);
console.log(` Average health: ${dashboard.avgHealth}%`);
console.log(` Health - Excellent: ${dashboard.healthBreakdown.excellent}, Good: ${dashboard.healthBreakdown.good}, Poor: ${dashboard.healthBreakdown.poor}`);
console.log(` Feeding - Fed: ${dashboard.feeding.fed}, Hungry: ${dashboard.feeding.hungry}`);
// Alerts
const alerts = this.getCriticalAlerts();
if (alerts.length > 0) {
console.log("\nCRITICAL ALERTS");
alerts.forEach((alert, i) => {
console.log(` ${i + 1}. [${alert.priority}] ${alert.name} (Sector ${alert.sector}): ${alert.issue}`);
});
} else {
console.log("\nNo critical alerts");
}
// Ranking
const ranking = this.getHealthRanking(5);
console.log("\nTOP 5 - HEALTH RANKING");
ranking.forEach((d, i) => {
console.log(` ${i + 1}. ${d.name} (${d.species}) - ${d.health}% - Sector ${d.sector}`);
});
// Sector analysis
const sectorAnalysis = this.getSectorAnalysis();
console.log("\nSECTOR ANALYSIS");
sectorAnalysis.forEach(sector => {
console.log(` Sector ${sector.sector}:`);
console.log(` Dinosaurs: ${sector.count} - Average health: ${sector.avgHealth}%`);
console.log(` Carnivores: ${sector.carnivores}, Hungry: ${sector.unfed}`);
console.log(` List: ${sector.dinosaurs.join(", ")}`);
});
}
}
// Run the reporting system
const reportSystem = new ParkReportingSystem(dinosaurs);
reportSystem.displayFullReport();
console.log("\nCongratulations! You've mastered advanced iterations!");Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What is the key difference between map() and forEach()?
2. What is the reduce() method on an array used for?
Hands-on tasks in the game
- Horizontal ordering
Arrange the elements of filtering and mapping an array: