JavaScript and TypeScript course · Module 2: Functions, Arrays and Objects
Basic Array Methods in JavaScript
In this lesson3
Welcome back to Jurassic Park! In the previous lesson, we learned the basics of arrays in JavaScript. Now we will dive into the basic array methods that are essential for everyday data work. These methods allow you to add, remove, and manipulate elements in arrays, which is crucial for managing the dinosaur inventory, planning feedings, and organizing park staff.
Modifying Arrays - Mutating Methods
First, let's look at methods that modify the original array. These are called mutating methods.
1. push() - Adding Elements to the End of an Array
The push() method adds one or more elements to the end of an array and returns the new length of the array:
// Managing dinosaur species in our enclosure
const dinoEnclosure = ["T-Rex", "Velociraptor"];
// Adding a new dinosaur species
dinoEnclosure.push("Dilophosaurus");
console.log(dinoEnclosure); // ["T-Rex", "Velociraptor", "Dilophosaurus"]
// Adding several species at once
const newLength = dinoEnclosure.push("Gallimimus", "Compsognathus");
console.log(dinoEnclosure);
// ["T-Rex", "Velociraptor", "Dilophosaurus", "Gallimimus", "Compsognathus"]
console.log(`Current number of species in enclosure: ${newLength}`); // 5When to use push():
- When you need to add element(s) to the end of an array
- When you want to track the new array length after adding elements
- When the order of elements matters and the new element should go at the end
2. pop() - Removing the Last Element
The pop() method removes the last element from an array and returns that element:
// List of dinosaurs in our enclosure
const dinoEnclosure = ["T-Rex", "Velociraptor", "Dilophosaurus", "Compsognathus"];
// Moving the last dinosaur to a new enclosure
const removedDino = dinoEnclosure.pop();
console.log(`Moved dinosaur: ${removedDino}`); // "Compsognathus"
console.log("Remaining dinosaurs:", dinoEnclosure); // ["T-Rex", "Velociraptor", "Dilophosaurus"]
// We can continue removing
const anotherRemovedDino = dinoEnclosure.pop();
console.log(`Moved another dinosaur: ${anotherRemovedDino}`); // "Dilophosaurus"
console.log("Current enclosure contents:", dinoEnclosure); // ["T-Rex", "Velociraptor"]When to use pop():
- When you need to remove the last element from an array
- When you need to retrieve the value of the removed element
- When implementing stack data structures (LIFO - Last In, First Out)
3. unshift() - Adding Elements to the Beginning
The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array:
// Queue of dinosaurs waiting for examination
const dinoQueue = ["Velociraptor", "Triceratops"];
// Priority addition of T-Rex to the front of the queue
dinoQueue.unshift("T-Rex");
console.log("Current queue:", dinoQueue); // ["T-Rex", "Velociraptor", "Triceratops"]
// Adding several dinosaurs at once to the front
const newQueueSize = dinoQueue.unshift("Brachiosaurus", "Stegosaurus");
console.log("Current queue:", dinoQueue);
// ["Brachiosaurus", "Stegosaurus", "T-Rex", "Velociraptor", "Triceratops"]
console.log(`Number of dinosaurs in queue: ${newQueueSize}`); // 5When to use unshift():
- When you want to add an element to the beginning of an array
- When implementing priority queues where higher-priority elements go to the front
- When you need to track the new array length
4. shift() - Removing the First Element
The shift() method removes the first element from an array and returns that element:
// Queue of dinosaurs waiting for examination
const dinoQueue = ["T-Rex", "Velociraptor", "Triceratops", "Stegosaurus"];
// Getting the first dinosaur for examination
const nextDino = dinoQueue.shift();
console.log(`Examining dinosaur: ${nextDino}`); // "T-Rex"
console.log("Remaining queue:", dinoQueue); // ["Velociraptor", "Triceratops", "Stegosaurus"]
// Processing the next dinosaur
const anotherDino = dinoQueue.shift();
console.log(`Next dinosaur for examination: ${anotherDino}`); // "Velociraptor"
console.log("Current queue state:", dinoQueue); // ["Triceratops", "Stegosaurus"]When to use shift():
- When you need to remove and retrieve the first element of an array
- When implementing queues (FIFO - First In, First Out)
- When processing elements in the order they were added
5. splice() - Modifying Elements at Any Position
The splice() method changes the contents of an array by removing, replacing, or adding elements. It is extremely versatile because it allows modification of the array at any position.
Basic syntax: array.splice(startIndex, deleteCount, item1, item2, ...):
startIndex: the index at which to start the changedeleteCount: the number of elements to removeitem1, item2, ...: (optional) elements to add
5.1. Removing Elements with splice()
// List of dinosaur species in the park
const dinosaurs = ["T-Rex", "Velociraptor", "Triceratops", "Stegosaurus", "Brachiosaurus"];
// Remove 2 elements starting from index 1 (the second element)
const removedDinos = dinosaurs.splice(1, 2);
console.log("Removed dinosaurs:", removedDinos); // ["Velociraptor", "Triceratops"]
console.log("Remaining dinosaurs:", dinosaurs); // ["T-Rex", "Stegosaurus", "Brachiosaurus"]5.2. Replacing Elements with splice()
// List of dinosaur species
const dinosaurs = ["T-Rex", "Dilophosaurus", "Triceratops", "Stegosaurus"];
// Replace Dilophosaurus with Velociraptor
const replaced = dinosaurs.splice(1, 1, "Velociraptor");
console.log("Replaced dinosaur:", replaced); // ["Dilophosaurus"]
console.log("Current list:", dinosaurs); // ["T-Rex", "Velociraptor", "Triceratops", "Stegosaurus"]
// Replace multiple elements at once
dinosaurs.splice(2, 2, "Brachiosaurus", "Ankylosaurus", "Parasaurolophus");
console.log("New roster:", dinosaurs);
// ["T-Rex", "Velociraptor", "Brachiosaurus", "Ankylosaurus", "Parasaurolophus"]5.3. Adding Elements Without Removing
// List of dinosaur species
const dinosaurs = ["T-Rex", "Velociraptor"];
// Add new species at index 1 (between T-Rex and Velociraptor)
dinosaurs.splice(1, 0, "Dilophosaurus", "Compsognathus");
console.log(dinosaurs); // ["T-Rex", "Dilophosaurus", "Compsognathus", "Velociraptor"]When to use splice():
- When you need to modify an array at a specific position, not just at the end or beginning
- When you need to remove and/or add elements simultaneously
- When you want to replace a section of an array with new values
6. sort() - Sorting an Array
The sort() method sorts the elements of an array in place and returns the sorted array:
// List of dinosaurs for feeding
const feedingList = ["Velociraptor", "T-Rex", "Dilophosaurus", "Gallimimus", "Compsognathus"];
// Alphabetical sorting
feedingList.sort();
console.log("Feeding list (alphabetical):", feedingList);
// ["Compsognathus", "Dilophosaurus", "Gallimimus", "T-Rex", "Velociraptor"]
// Array with dinosaur sizes (in cm)
const dinoSizes = [1200, 300, 800, 2000, 40];
// Default sort treats numbers as strings - this won't work correctly!
dinoSizes.sort();
console.log("Incorrectly sorted sizes:", dinoSizes);
// Probably: [1200, 2000, 300, 40, 800] - incorrect!
// Correct number sorting with a compare function
dinoSizes.sort((a, b) => a - b);
console.log("Correctly sorted sizes (ascending):", dinoSizes);
// [40, 300, 800, 1200, 2000]
// Descending sort
dinoSizes.sort((a, b) => b - a);
console.log("Sizes sorted descending:", dinoSizes);
// [2000, 1200, 800, 300, 40]Sorting Objects
// Dinosaur data for feeding
const dinosaurs = [
{ name: "T-Rex", weight: 7000, priority: 1 },
{ name: "Velociraptor", weight: 100, priority: 2 },
{ name: "Triceratops", weight: 9000, priority: 3 },
{ name: "Gallimimus", weight: 450, priority: 4 }
];
// Sort by feeding priority
dinosaurs.sort((a, b) => a.priority - b.priority);
console.log("Feeding order by priority:");
dinosaurs.forEach(dino => console.log(`${dino.name} (priority: ${dino.priority})`));
// Sort by weight (heaviest first)
dinosaurs.sort((a, b) => b.weight - a.weight);
console.log("\nOrder by weight (heaviest first):");
dinosaurs.forEach(dino => console.log(`${dino.name} (${dino.weight} kg)`));
// Sort alphabetically by name
dinosaurs.sort((a, b) => a.name.localeCompare(b.name));
console.log("\nDinosaurs alphabetically:");
dinosaurs.forEach(dino => console.log(`${dino.name}`));The sort() method takes an optional compare function that should return:
- A negative value if a should be before b
- Zero if a and b are equivalent in terms of sorting
- A positive value if a should be after b
When to use sort():
- When you need to order array elements by a specific criterion
- When working with lists that must be presented in a specific order
- When implementing sorting functionality in an application
7. reverse() - Reversing Array Order
The reverse() method reverses the order of elements in an array and returns the reversed array:
// List of dinosaurs from oldest to youngest
const dinosaursByAge = ["Brachiosaurus", "Stegosaurus", "Triceratops", "Velociraptor", "T-Rex"];
// Reverse the order to get youngest to oldest
dinosaursByAge.reverse();
console.log("From youngest to oldest:", dinosaursByAge);
// ["T-Rex", "Velociraptor", "Triceratops", "Stegosaurus", "Brachiosaurus"]
// Often used in combination with sort()
const dinoHeights = [500, 900, 200, 1200, 350];
// Descending sort by sorting ascending + reversing
dinoHeights.sort((a, b) => a - b).reverse();
console.log("Heights descending:", dinoHeights);
// [1200, 900, 500, 350, 200]When to use reverse():
- When you need to reverse the order of elements in an array
- When you want to switch from ascending to descending order (or vice versa) after sorting
- When implementing a "reverse order" feature in a user interface
8. fill() - Filling an Array with a Value
The fill() method fills all elements of an array from a start index to an end index (not including) with a specified value:
// Preparing an array for dinosaur temperature readings (10 readings)
const temperatures = new Array(10);
// Fill with a default value (38.5 degrees Celsius)
temperatures.fill(38.5);
console.log("Default temperatures:", temperatures);
// [38.5, 38.5, 38.5, 38.5, 38.5, 38.5, 38.5, 38.5, 38.5, 38.5]
// Fill only part of the array
temperatures.fill(39.2, 2, 5); // From index 2 (inclusive) to 5 (exclusive)
console.log("Updated temperatures:", temperatures);
// [38.5, 38.5, 39.2, 39.2, 39.2, 38.5, 38.5, 38.5, 38.5, 38.5]
// Using with a new array and negative indices (counted from the end)
const feedingSchedule = new Array(7).fill("Standard");
feedingSchedule.fill("Extra portion", -3); // Last 3 days
console.log("Weekly feeding plan:", feedingSchedule);
// ["Standard", "Standard", "Standard", "Standard", "Extra portion", "Extra portion", "Extra portion"]When to use fill():
- When creating a new array and need to fill it with a specific initial value
- When you need to replace all or some values in an existing array
- When initializing arrays to store data with default values
Applying Basic Array Methods in Practice
Now let's combine the methods we've learned to solve more practical scenarios in our Jurassic Park:
Example 1: Dinosaur Food Management System
// Dinosaur food management system
const feedingSystem = {
// System state
foodInventory: [],
feedingQueue: [],
feedingHistory: [],
// Adding a new food supply
addFoodSupply: function(type, quantity, expirationDate) {
const supply = { type, quantity, expirationDate, addedOn: new Date() };
this.foodInventory.push(supply);
// Sort by expiration date (soonest first)
this.foodInventory.sort((a, b) =>
new Date(a.expirationDate) - new Date(b.expirationDate)
);
console.log(`Added ${quantity}kg of "${type}" food to supplies.`);
return supply;
},
// Adding a dinosaur to the feeding queue
scheduleDinoFeeding: function(dinoId, dinoName, foodType, quantity, priority) {
const feedingRequest = {
dinoId,
dinoName,
foodType,
quantity,
priority,
scheduledAt: new Date()
};
if (priority === "high") {
// Add to the front of the queue
this.feedingQueue.unshift(feedingRequest);
} else {
// Add to the end of the queue
this.feedingQueue.push(feedingRequest);
}
console.log(`Scheduled feeding for ${dinoName} (priority: ${priority})`);
return this.feedingQueue.length;
},
// Getting the next dinosaur to feed
getNextDinoToFeed: function() {
if (this.feedingQueue.length === 0) {
console.log("All dinosaurs fed. Queue empty.");
return null;
}
const nextFeeding = this.feedingQueue.shift();
console.log(`Next to feed: ${nextFeeding.dinoName}`);
return nextFeeding;
},
// Dispensing food from the warehouse
dispenseFoodForDino: function(dinoFeeding) {
const { foodType, quantity, dinoName } = dinoFeeding;
// Search for the appropriate food supply
let remainingQuantity = quantity;
const usedSupplies = [];
// Iterate from the oldest supply (expires soonest)
for (let i = 0; i < this.foodInventory.length && remainingQuantity > 0; i++) {
const supply = this.foodInventory[i];
if (supply.type === foodType && supply.quantity > 0) {
// How much we can take from this supply
const amountToTake = Math.min(remainingQuantity, supply.quantity);
supply.quantity -= amountToTake;
remainingQuantity -= amountToTake;
usedSupplies.push({
type: supply.type,
amount: amountToTake,
expirationDate: supply.expirationDate
});
// If the supply is empty, remove it from inventory
if (supply.quantity === 0) {
this.foodInventory.splice(i, 1);
i--; // Adjust index after removing element
}
}
}
// Add record to feeding history
const feedingRecord = {
...dinoFeeding,
fedAt: new Date(),
suppliesUsed: usedSupplies,
fullyFed: remainingQuantity === 0
};
this.feedingHistory.push(feedingRecord);
if (remainingQuantity > 0) {
console.log(`WARNING: Missing ${remainingQuantity}kg of "${foodType}" food for ${dinoName}!`);
return false;
}
console.log(`Fed ${dinoName} using ${quantity}kg of "${foodType}" food.`);
return feedingRecord;
},
// Performing a full feeding cycle
processFeedingCycle: function(maxFeedings = 5) {
console.log("=== STARTING FEEDING CYCLE ===");
let feedingsProcessed = 0;
// Process a specified number of feedings or until the queue is empty
while (feedingsProcessed < maxFeedings && this.feedingQueue.length > 0) {
const nextDino = this.getNextDinoToFeed();
if (nextDino) {
const result = this.dispenseFoodForDino(nextDino);
if (!result) {
// If feeding failed, move the dinosaur to the end of the queue
this.feedingQueue.push({
...nextDino,
priority: "high", // Raise priority for unfed dinosaur
scheduledAt: new Date()
});
console.log(`${nextDino.dinoName} moved to end of queue with high priority.`);
}
feedingsProcessed++;
}
}
console.log(`=== FEEDING CYCLE COMPLETE (processed: ${feedingsProcessed}) ===`);
console.log(`Remaining in queue: ${this.feedingQueue.length} dinosaurs`);
return feedingsProcessed;
},
// Reporting inventory status
reportInventoryStatus: function() {
console.log("=== INVENTORY STATUS REPORT ===");
if (this.foodInventory.length === 0) {
console.log("Warehouse is empty! Order new food supplies!");
return { isEmpty: true, totalQuantity: 0, types: [] };
}
// Group supplies by type
const inventory = this.foodInventory.reduce((acc, supply) => {
if (!acc[supply.type]) {
acc[supply.type] = 0;
}
acc[supply.type] += supply.quantity;
return acc;
}, {});
// Calculate total quantity
const totalQuantity = Object.values(inventory).reduce((sum, qty) => sum + qty, 0);
console.log(`Total food supply: ${totalQuantity}kg`);
Object.entries(inventory).forEach(([type, qty]) => {
console.log(`- ${type}: ${qty}kg`);
});
// Check supplies expiring soon (within 3 days)
const today = new Date();
const threeDaysLater = new Date(today);
threeDaysLater.setDate(today.getDate() + 3);
const expiringSupplies = this.foodInventory.filter(supply =>
new Date(supply.expirationDate) <= threeDaysLater
);
if (expiringSupplies.length > 0) {
console.log("\nSupplies expiring within 3 days:");
expiringSupplies.forEach(supply => {
console.log(`- ${supply.quantity}kg ${supply.type} (expires: ${supply.expirationDate})`);
});
}
return {
isEmpty: false,
totalQuantity,
types: Object.keys(inventory),
inventory,
expiringSupplies
};
}
};
// System demonstration
console.log("=== FOOD MANAGEMENT SYSTEM DEMONSTRATION ===");
// 1. Adding food supplies
feedingSystem.addFoodSupply("Meat", 500, "2023-07-15");
feedingSystem.addFoodSupply("Plants", 800, "2023-07-10");
feedingSystem.addFoodSupply("Fish", 200, "2023-07-05");
feedingSystem.addFoodSupply("Meat", 300, "2023-07-20");
// 2. Scheduling feedings
feedingSystem.scheduleDinoFeeding("TRX-01", "Rex", "Meat", 150, "high");
feedingSystem.scheduleDinoFeeding("VEL-02", "Blue", "Meat", 50, "normal");
feedingSystem.scheduleDinoFeeding("TRCP-03", "Trixie", "Plants", 120, "normal");
feedingSystem.scheduleDinoFeeding("BRCH-04", "Bronty", "Plants", 250, "normal");
feedingSystem.scheduleDinoFeeding("STEG-05", "Spike", "Plants", 100, "high");
// 3. Inventory status report before feeding
feedingSystem.reportInventoryStatus();
// 4. Processing feeding cycle
feedingSystem.processFeedingCycle(3); // Process only 3 feedings
// 5. Check inventory status after feeding
feedingSystem.reportInventoryStatus();
// 6. Complete the feeding cycle
feedingSystem.processFeedingCycle(5); // Process remaining feedings
// 7. Check inventory status after full cycle
feedingSystem.reportInventoryStatus();Example 2: Park Staff Team Management
// Jurassic Park staff team management system
const staffManagementSystem = {
// System data
departments: [
{ id: "OPS", name: "Operations" },
{ id: "SCI", name: "Scientific Research" },
{ id: "SEC", name: "Security" },
{ id: "VET", name: "Veterinary" },
{ id: "MAINT", name: "Maintenance" }
],
staff: [],
teams: [],
// Adding a new employee
addStaffMember: function(name, role, skills, departmentId) {
// Check if department exists
const department = this.departments.find(dept => dept.id === departmentId);
if (!department) {
console.log(`Error: Department with ID "${departmentId}" does not exist.`);
return null;
}
// Generate employee ID
const id = `${departmentId}-${(this.staff.length + 1).toString().padStart(3, '0')}`;
const staffMember = {
id,
name,
role,
skills: Array.isArray(skills) ? skills : [skills],
departmentId,
departmentName: department.name,
hireDate: new Date().toISOString().split('T')[0]
};
this.staff.push(staffMember);
console.log(`Added employee: ${name} (${role}) to department ${department.name}`);
return staffMember;
},
// Creating a new team
createTeam: function(name, mission, leaderId) {
// Check if leader exists
const leader = this.staff.find(person => person.id === leaderId);
if (!leader) {
console.log(`Error: Employee with ID "${leaderId}" does not exist.`);
return null;
}
const teamId = `TEAM-${(this.teams.length + 1).toString().padStart(3, '0')}`;
const team = {
id: teamId,
name,
mission,
createdAt: new Date().toISOString().split('T')[0],
leaderId,
leaderName: leader.name,
members: [leaderId],
status: "active"
};
this.teams.push(team);
console.log(`Created team: ${name} (mission: ${mission}), leader: ${leader.name}`);
return team;
},
// Adding an employee to a team
addMemberToTeam: function(teamId, memberId) {
// Find team
const teamIndex = this.teams.findIndex(team => team.id === teamId);
if (teamIndex === -1) {
console.log(`Error: Team with ID "${teamId}" does not exist.`);
return false;
}
// Find employee
const member = this.staff.find(person => person.id === memberId);
if (!member) {
console.log(`Error: Employee with ID "${memberId}" does not exist.`);
return false;
}
// Check if employee is already in the team
if (this.teams[teamIndex].members.includes(memberId)) {
console.log(`${member.name} is already a member of team ${this.teams[teamIndex].name}.`);
return false;
}
// Add employee to team
this.teams[teamIndex].members.push(memberId);
console.log(`Added ${member.name} to team ${this.teams[teamIndex].name}.`);
return true;
},
// Removing an employee from a team
removeMemberFromTeam: function(teamId, memberId) {
// Find team
const teamIndex = this.teams.findIndex(team => team.id === teamId);
if (teamIndex === -1) {
console.log(`Error: Team with ID "${teamId}" does not exist.`);
return false;
}
// Check if employee is the leader
if (this.teams[teamIndex].leaderId === memberId) {
console.log(`Error: Cannot remove the team leader. Change the leader first.`);
return false;
}
// Find employee index in the team
const memberIndex = this.teams[teamIndex].members.indexOf(memberId);
if (memberIndex === -1) {
console.log(`Employee is not a member of team ${this.teams[teamIndex].name}.`);
return false;
}
// Find employee for informational purposes
const member = this.staff.find(person => person.id === memberId);
// Remove employee from team
this.teams[teamIndex].members.splice(memberIndex, 1);
console.log(`Removed ${member ? member.name : memberId} from team ${this.teams[teamIndex].name}.`);
return true;
},
// Changing team leader
changeTeamLeader: function(teamId, newLeaderId) {
// Find team
const teamIndex = this.teams.findIndex(team => team.id === teamId);
if (teamIndex === -1) {
console.log(`Error: Team with ID "${teamId}" does not exist.`);
return false;
}
// Check if new leader exists
const newLeader = this.staff.find(person => person.id === newLeaderId);
if (!newLeader) {
console.log(`Error: Employee with ID "${newLeaderId}" does not exist.`);
return false;
}
// Check if new leader is a team member
if (!this.teams[teamIndex].members.includes(newLeaderId)) {
// Add new leader to team if not already a member
this.teams[teamIndex].members.push(newLeaderId);
console.log(`${newLeader.name} was added to the team as the new leader.`);
}
// Save old leader info for the message
const oldLeaderId = this.teams[teamIndex].leaderId;
const oldLeader = this.staff.find(person => person.id === oldLeaderId);
// Update leader
this.teams[teamIndex].leaderId = newLeaderId;
this.teams[teamIndex].leaderName = newLeader.name;
console.log(`Team ${this.teams[teamIndex].name} leader changed from ${oldLeader.name} to ${newLeader.name}.`);
return true;
},
// Deactivating a team
deactivateTeam: function(teamId, reason) {
// Find team
const teamIndex = this.teams.findIndex(team => team.id === teamId);
if (teamIndex === -1) {
console.log(`Error: Team with ID "${teamId}" does not exist.`);
return false;
}
// Save state before modification
const teamName = this.teams[teamIndex].name;
// Update team status
this.teams[teamIndex].status = "inactive";
this.teams[teamIndex].deactivatedAt = new Date().toISOString().split('T')[0];
this.teams[teamIndex].deactivationReason = reason || "Unspecified";
console.log(`Team ${teamName} has been deactivated. Reason: ${this.teams[teamIndex].deactivationReason}`);
return true;
},
// Generating a teams report
generateTeamsReport: function(includeInactive = false) {
console.log("=== JURASSIC PARK TEAMS REPORT ===");
// Filter teams by status if not including inactive
const teamsToReport = includeInactive
? this.teams
: this.teams.filter(team => team.status === "active");
if (teamsToReport.length === 0) {
console.log("No teams to display.");
return { teams: [] };
}
// Prepare report data
const teamsData = teamsToReport.map(team => {
// Get full member information
const memberDetails = team.members.map(memberId => {
const member = this.staff.find(person => person.id === memberId);
return member ? {
id: member.id,
name: member.name,
role: member.role,
isLeader: memberId === team.leaderId
} : { id: memberId, name: "Unknown", role: "Unknown", isLeader: false };
});
return {
id: team.id,
name: team.name,
mission: team.mission,
status: team.status,
memberCount: team.members.length,
leader: this.staff.find(person => person.id === team.leaderId),
members: memberDetails,
createdAt: team.createdAt,
deactivatedAt: team.deactivatedAt,
deactivationReason: team.deactivationReason
};
});
// Sort teams - active first, then by creation date
teamsData.sort((a, b) => {
if (a.status !== b.status) {
return a.status === "active" ? -1 : 1;
}
return new Date(b.createdAt) - new Date(a.createdAt);
});
// Display summary
console.log(`Number of teams: ${teamsData.length}`);
console.log(`Active teams: ${teamsData.filter(t => t.status === "active").length}`);
if (includeInactive) {
console.log(`Inactive teams: ${teamsData.filter(t => t.status === "inactive").length}`);
}
// Display details for each team
teamsData.forEach(team => {
console.log(`\n${team.id}: ${team.name} (Status: ${team.status})`);
console.log(`Mission: ${team.mission}`);
console.log(`Leader: ${team.leader ? team.leader.name : 'None'} (${team.leader ? team.leader.role : ''})`);
console.log(`Number of members: ${team.memberCount}`);
console.log("Members:");
team.members.forEach(member => {
console.log(` - ${member.name} (${member.role})${member.isLeader ? ' [LEADER]' : ''}`);
});
if (team.status === "inactive") {
console.log(`Deactivated: ${team.deactivatedAt}`);
console.log(`Reason: ${team.deactivationReason}`);
}
});
return { teams: teamsData };
},
// Reorganizing teams
reorganizeTeams: function(fromTeamId, toTeamId, memberIds, dissolveSourceTeam = false) {
// Check if teams exist
const fromTeamIndex = this.teams.findIndex(team => team.id === fromTeamId);
const toTeamIndex = this.teams.findIndex(team => team.id === toTeamId);
if (fromTeamIndex === -1 || toTeamIndex === -1) {
console.log(`Error: One or both teams do not exist.`);
return false;
}
// Check if teams are active
if (this.teams[fromTeamIndex].status !== "active" || this.teams[toTeamIndex].status !== "active") {
console.log(`Error: Teams must be active to reorganize them.`);
return false;
}
// If no specific members specified, transfer all (except leader)
const membersToMove = memberIds ||
this.teams[fromTeamIndex].members.filter(id => id !== this.teams[fromTeamIndex].leaderId);
// Transfer members
for (const memberId of membersToMove) {
// Check if employee is part of the source team
if (!this.teams[fromTeamIndex].members.includes(memberId)) {
console.log(`Error: Employee with ID ${memberId} is not a member of the source team.`);
continue;
}
// Check if employee is the leader (if we don't want to transfer everyone)
if (memberIds && memberId === this.teams[fromTeamIndex].leaderId) {
console.log(`Cannot transfer team leader. Change the leader first.`);
continue;
}
// Check if employee is already part of the target team
if (this.teams[toTeamIndex].members.includes(memberId)) {
console.log(`Employee with ID ${memberId} is already a member of the target team.`);
continue;
}
// Remove from original team
const fromIndex = this.teams[fromTeamIndex].members.indexOf(memberId);
this.teams[fromTeamIndex].members.splice(fromIndex, 1);
// Add to new team
this.teams[toTeamIndex].members.push(memberId);
// Find employee name for logs
const member = this.staff.find(person => person.id === memberId);
console.log(`Transferred ${member ? member.name : memberId} from team ${this.teams[fromTeamIndex].name} to ${this.teams[toTeamIndex].name}`);
}
// If chosen to dissolve source team and no members left
if (dissolveSourceTeam || this.teams[fromTeamIndex].members.length === 0) {
this.deactivateTeam(fromTeamId, "Reorganization - team transferred");
}
return true;
}
};
// Staff team management system demonstration
console.log("=== STAFF TEAM MANAGEMENT SYSTEM DEMONSTRATION ===");
// 1. Adding employees
const owen = staffManagementSystem.addStaffMember("Owen Grady", "Dinosaur Trainer", ["Animal behavior", "Training", "First aid"], "OPS");
const claire = staffManagementSystem.addStaffMember("Claire Dearing", "Operations Director", ["Management", "Marketing", "Administration"], "OPS");
const dr_wu = staffManagementSystem.addStaffMember("Dr. Henry Wu", "Chief Geneticist", ["Genetics", "Bioengineering", "Cloning"], "SCI");
const barry = staffManagementSystem.addStaffMember("Barry", "Assistant Trainer", ["Training", "Animal care"], "OPS");
const lowery = staffManagementSystem.addStaffMember("Lowery Cruthers", "Systems Technician", ["IT", "Monitoring", "Communication"], "SEC");
const vivian = staffManagementSystem.addStaffMember("Vivian Krill", "Security Coordinator", ["Security", "Communication", "Crisis management"], "SEC");
const muldoon = staffManagementSystem.addStaffMember("Robert Muldoon", "Security Specialist", ["Firearms", "Security", "Tracking"], "SEC");
const malcolm = staffManagementSystem.addStaffMember("Dr. Ian Malcolm", "Mathematician", ["Chaos theory", "Risk analysis", "Modeling"], "SCI");
const sattler = staffManagementSystem.addStaffMember("Dr. Ellie Sattler", "Paleobotanist", ["Botany", "Paleontology", "Ecology"], "SCI");
const harding = staffManagementSystem.addStaffMember("Dr. Gerry Harding", "Veterinarian", ["Veterinary medicine", "Zoology", "Medicine"], "VET");
// 2. Creating teams
const raptorTeam = staffManagementSystem.createTeam("Velociraptor Team", "Training and care of Velociraptors", owen.id);
staffManagementSystem.addMemberToTeam(raptorTeam.id, barry.id);
const securityTeam = staffManagementSystem.createTeam("Security Team", "Ensuring park safety", muldoon.id);
staffManagementSystem.addMemberToTeam(securityTeam.id, vivian.id);
staffManagementSystem.addMemberToTeam(securityTeam.id, lowery.id);
const scienceTeam = staffManagementSystem.createTeam("Science Team", "Scientific research and development", dr_wu.id);
staffManagementSystem.addMemberToTeam(scienceTeam.id, malcolm.id);
staffManagementSystem.addMemberToTeam(scienceTeam.id, sattler.id);
// 3. Teams report
staffManagementSystem.generateTeamsReport();
// 4. Team reorganization
console.log("\n=== TEAM REORGANIZATION ===");
// Creating a new crisis management team
const crisisTeam = staffManagementSystem.createTeam("Crisis Management Team", "Responding to crisis situations", claire.id);
// Transferring members from other teams
staffManagementSystem.reorganizeTeams(securityTeam.id, crisisTeam.id, [vivian.id]);
staffManagementSystem.addMemberToTeam(crisisTeam.id, malcolm.id); // Adding Malcolm as risk advisor
staffManagementSystem.addMemberToTeam(crisisTeam.id, harding.id); // Adding veterinarian
// Changing science team leader
staffManagementSystem.changeTeamLeader(scienceTeam.id, sattler.id);
// Deactivating one team
staffManagementSystem.deactivateTeam(raptorTeam.id, "Project suspended - raptor incident");
// 5. Final teams report (including inactive)
staffManagementSystem.generateTeamsReport(true);Summary
In this lesson, we learned the basic array modification methods in JavaScript:
- push() - adds elements to the end of an array
- pop() - removes and returns the last element of an array
- unshift() - adds elements to the beginning of an array
- shift() - removes and returns the first element of an array
- splice() - adds, removes, or replaces elements at any position in an array
- sort() - sorts array elements
- reverse() - reverses the order of array elements
- fill() - fills array elements with a specified value
The ability to effectively use these methods is crucial when working with data in JavaScript. They allow you to manage collections, implement data structures (such as stacks and queues), and efficiently manipulate data.
It is worth remembering that the above methods modify the original array (except when you create a copy before applying them). In one of the upcoming lessons, we will learn array methods that do not modify the original but return a new array or value.
Code for this lesson: index.js
// Array methods - Jurassic Park
console.log("Array Methods Laboratory");
console.log("Advanced operations on collections\n");
// ===========================================
// 1. forEach() - ITERATION
// ===========================================
console.log("=== 1. forEach() - Iteration ===");
const dinosaurs = ["T-Rex", "Velociraptor", "Triceratops", "Stegosaurus"];
console.log("\nDinosaur list:");
dinosaurs.forEach((dino, index) => {
console.log(` ${index + 1}. ${dino}`);
});
// forEach with full parameters
console.log("\nFull forEach version:");
dinosaurs.forEach((element, index, array) => {
console.log(` [${index}] ${element} from an array of length ${array.length}`);
});
// ===========================================
// 2. map() - TRANSFORMATION
// ===========================================
console.log("\n=== 2. map() - Transformation ===");
const dinoData = [
{ name: "T-Rex", weight: 8000 },
{ name: "Velociraptor", weight: 80 },
{ name: "Triceratops", weight: 9000 }
];
// Extracting just the names
const names = dinoData.map(dino => dino.name);
console.log("\nNames only:", names);
// Transformation to a new format
const formatted = dinoData.map(dino => ({
species: dino.name,
weightInTons: dino.weight / 1000,
category: dino.weight > 1000 ? "Large" : "Small"
}));
console.log("\nTransformed:");
formatted.forEach(d => {
console.log(` ${d.species}: ${d.weightInTons}t - ${d.category}`);
});
// ===========================================
// 3. filter() - FILTERING
// ===========================================
console.log("\n=== 3. filter() - Filtering ===");
const allDinos = [
{ name: "T-Rex", weight: 8000, carnivore: true },
{ name: "Velociraptor", weight: 80, carnivore: true },
{ name: "Triceratops", weight: 9000, carnivore: false },
{ name: "Stegosaurus", weight: 5000, carnivore: false },
{ name: "Brachiosaurus", weight: 50000, carnivore: false }
];
// Only carnivores
const carnivores = allDinos.filter(dino => dino.carnivore);
console.log("\nCarnivores:", carnivores.map(d => d.name));
// Heavy dinosaurs (> 5000kg)
const heavy = allDinos.filter(dino => dino.weight > 5000);
console.log("Heavy (>5t):", heavy.map(d => d.name));
// Combining conditions
const heavyCarnivores = allDinos.filter(d => d.carnivore && d.weight > 100);
console.log("Heavy carnivores:", heavyCarnivores.map(d => d.name));
// ===========================================
// 4. find() and findIndex()
// ===========================================
console.log("\n=== 4. find() and findIndex() ===");
const park = [
{ id: 1, name: "T-Rex", sector: "A" },
{ id: 2, name: "Velociraptor", sector: "B" },
{ id: 3, name: "Triceratops", sector: "C" }
];
// find() - first element satisfying the condition
const foundDino = park.find(dino => dino.sector === "B");
console.log("\nfind(sector === 'B'):", foundDino);
// findIndex() - index of the first element
const foundIndex = park.findIndex(dino => dino.name === "Triceratops");
console.log("findIndex(name === 'Triceratops'):", foundIndex);
// Element not found
const notFound = park.find(dino => dino.name === "Pteranodon");
console.log("find(Pteranodon):", notFound); // undefined
// ===========================================
// 5. reduce() - AGGREGATION
// ===========================================
console.log("\n=== 5. reduce() - Aggregation ===");
const weights = [
{ name: "T-Rex", weight: 8000 },
{ name: "Velociraptor", weight: 80 },
{ name: "Triceratops", weight: 9000 },
{ name: "Stegosaurus", weight: 5000 }
];
// Sum of weights
const totalWeight = weights.reduce((sum, dino) => sum + dino.weight, 0);
console.log(`\nTotal weight: ${totalWeight}kg`);
// Average weight
const avgWeight = totalWeight / weights.length;
console.log(`Average weight: ${avgWeight.toFixed(2)}kg`);
// Grouping by weight
const grouped = weights.reduce((acc, dino) => {
const category = dino.weight > 1000 ? "heavy" : "light";
if (!acc[category]) acc[category] = [];
acc[category].push(dino.name);
return acc;
}, {});
console.log("\nGrouped:");
console.log(" Heavy:", grouped.heavy);
console.log(" Light:", grouped.light);
// Finding max
const heaviest = weights.reduce((max, dino) =>
dino.weight > max.weight ? dino : max
);
console.log(`\nHeaviest: ${heaviest.name} (${heaviest.weight}kg)`);
// ===========================================
// 6. some() and every()
// ===========================================
console.log("\n=== 6. some() and every() ===");
const herd = [
{ name: "Trike", health: 95 },
{ name: "Stego", health: 88 },
{ name: "Brachio", health: 72 }
];
// some() - checks whether at least one
const hasSick = herd.some(dino => dino.health < 80);
console.log("\nAre any sick (<80%):", hasSick);
const hasHealthy = herd.some(dino => dino.health > 90);
console.log("Are any very healthy (>90%):", hasHealthy);
// every() - checks whether all
const allHealthy = herd.every(dino => dino.health >= 80);
console.log("Are all healthy (≥80%):", allHealthy);
const allCritical = herd.every(dino => dino.health < 50);
console.log("Are all critical (<50%):", allCritical);
// ===========================================
// 7. sort() - SORTING
// ===========================================
console.log("\n=== 7. sort() - Sorting ===");
const unsorted = ["Velociraptor", "T-Rex", "Brachiosaurus", "Stegosaurus"];
// Alphabetically
const alphabetical = [...unsorted].sort();
console.log("\nAlphabetically:", alphabetical);
// Reverse alphabetically
const reverseAlpha = [...unsorted].sort((a, b) => b.localeCompare(a));
console.log("Reverse:", reverseAlpha);
// Sorting objects
const dinoStats = [
{ name: "T-Rex", health: 85 },
{ name: "Velociraptor", health: 100 },
{ name: "Triceratops", health: 70 }
];
const byHealth = [...dinoStats].sort((a, b) => b.health - a.health);
console.log("\nBy health (descending):");
byHealth.forEach(d => console.log(` ${d.name}: ${d.health}%`));
// ===========================================
// 8. CHAINING METHODS
// ===========================================
console.log("\n=== 8. Method chaining ===");
const inventory = [
{ name: "Rexy", species: "T-Rex", sector: "A", health: 95, carnivore: true },
{ name: "Blue", species: "Velociraptor", sector: "B", health: 100, carnivore: true },
{ name: "Charlie", species: "Velociraptor", sector: "B", health: 85, carnivore: true },
{ name: "Trike", species: "Triceratops", sector: "C", health: 70, carnivore: false },
{ name: "Stego", species: "Stegosaurus", sector: "C", health: 92, carnivore: false }
];
// Find healthy carnivores and sort by name
const healthyCarnivores = inventory
.filter(d => d.carnivore)
.filter(d => d.health >= 90)
.map(d => d.name)
.sort();
console.log("\nHealthy carnivores (≥90%):", healthyCarnivores);
// Sum of herbivore health
const herbivoreHealth = inventory
.filter(d => !d.carnivore)
.reduce((sum, d) => sum + d.health, 0);
console.log(`Sum of herbivore health: ${herbivoreHealth}%`);
// ===========================================
// 9. flat() and flatMap()
// ===========================================
console.log("\n=== 9. flat() and flatMap() ===");
const sectors = [
["T-Rex", "Spinosaurus"],
["Velociraptor", "Dilophosaurus"],
["Triceratops", "Stegosaurus"]
];
// flat() - flattening a nested array
const flatDinos = sectors.flat();
console.log("\nflat():", flatDinos);
// flatMap() - map + flat in one
const withEmoji = sectors.flatMap(sector =>
sector.map(dino => `${dino}`)
);
console.log("flatMap():", withEmoji);
// ===========================================
// 10. COMPLEX EXAMPLE
// ===========================================
console.log("\n=== 10. Analytics system - complex example ===");
class DinosaurAnalytics {
constructor(dinosaurs) {
this.dinosaurs = dinosaurs;
}
// General statistics
getOverallStats() {
const total = this.dinosaurs.length;
const avgHealth = this.dinosaurs.reduce((sum, d) => sum + d.health, 0) / total;
const carnivoreCount = this.dinosaurs.filter(d => d.carnivore).length;
return {
total,
avgHealth: avgHealth.toFixed(1),
carnivores: carnivoreCount,
herbivores: total - carnivoreCount
};
}
// Top N by health
getHealthiest(n = 3) {
return this.dinosaurs
.sort((a, b) => b.health - a.health)
.slice(0, n)
.map(d => ({ name: d.name, health: d.health }));
}
// Grouping by sector
groupBySector() {
return this.dinosaurs.reduce((acc, dino) => {
if (!acc[dino.sector]) acc[dino.sector] = [];
acc[dino.sector].push(dino.name);
return acc;
}, {});
}
// Alerts for sick ones
getHealthAlerts() {
return this.dinosaurs
.filter(d => d.health < 80)
.map(d => ({
name: d.name,
sector: d.sector,
health: d.health,
priority: d.health < 50 ? "CRITICAL" : "WARNING"
}))
.sort((a, b) => a.health - b.health);
}
// Sector report
getSectorReport(sector) {
const dinosInSector = this.dinosaurs.filter(d => d.sector === sector);
if (dinosInSector.length === 0) {
return { error: `No dinosaurs in sector ${sector}` };
}
const avgHealth = dinosInSector.reduce((sum, d) => sum + d.health, 0) / dinosInSector.length;
const carnivores = dinosInSector.filter(d => d.carnivore);
const herbivores = dinosInSector.filter(d => !d.carnivore);
return {
sector,
total: dinosInSector.length,
avgHealth: avgHealth.toFixed(1),
carnivores: carnivores.map(d => d.name),
herbivores: herbivores.map(d => d.name),
list: dinosInSector.map(d => `${d.name} (${d.health}%)`)
};
}
// Display all analyses
displayFullReport() {
console.log("\nFULL ANALYTICS REPORT");
console.log("=".repeat(70));
// General statistics
const stats = this.getOverallStats();
console.log("\nGeneral statistics:");
console.log(` Total dinosaurs: ${stats.total}`);
console.log(` Average health: ${stats.avgHealth}%`);
console.log(` Carnivores: ${stats.carnivores}`);
console.log(` Herbivores: ${stats.herbivores}`);
// Healthiest
const healthiest = this.getHealthiest(3);
console.log("\nTOP 3 - Healthiest:");
healthiest.forEach((d, i) => {
console.log(` ${i + 1}. ${d.name} - ${d.health}%`);
});
// Breakdown by sector
const sectors = this.groupBySector();
console.log("\nBreakdown by sector:");
Object.entries(sectors).sort().forEach(([sector, dinos]) => {
console.log(` Sector ${sector}: ${dinos.join(", ")}`);
});
// Health alerts
const alerts = this.getHealthAlerts();
if (alerts.length > 0) {
console.log("\nHEALTH ALERTS:");
alerts.forEach(alert => {
console.log(` [${alert.priority}] ${alert.name} - Sector ${alert.sector} - ${alert.health}%`);
});
} else {
console.log("\nNo health alerts");
}
// Sector reports
const uniqueSectors = [...new Set(this.dinosaurs.map(d => d.sector))].sort();
console.log("\nSECTOR DETAILS:");
uniqueSectors.forEach(sector => {
const report = this.getSectorReport(sector);
console.log(`\n Sector ${report.sector}:`);
console.log(` Dinosaurs: ${report.total}`);
console.log(` Average health: ${report.avgHealth}%`);
if (report.carnivores.length > 0) {
console.log(` Carnivores: ${report.carnivores.join(", ")}`);
}
if (report.herbivores.length > 0) {
console.log(` Herbivores: ${report.herbivores.join(", ")}`);
}
});
}
}
// Test data
const testData = [
{ name: "Rexy", species: "T-Rex", sector: "A", health: 95, carnivore: true },
{ name: "Blue", species: "Velociraptor", sector: "B", health: 100, carnivore: true },
{ name: "Charlie", species: "Velociraptor", sector: "B", health: 85, carnivore: true },
{ name: "Delta", species: "Velociraptor", sector: "B", health: 45, carnivore: true },
{ name: "Trike", species: "Triceratops", sector: "C", health: 70, carnivore: false },
{ name: "Stego", species: "Stegosaurus", sector: "C", health: 92, carnivore: false },
{ name: "Brachio", species: "Brachiosaurus", sector: "D", health: 88, carnivore: false }
];
// Run analysis
const analytics = new DinosaurAnalytics(testData);
analytics.displayFullReport();
console.log("\nCongratulations! You've mastered array methods!");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 does the Array.prototype.pop() method do?
2. What will typeof undefined return?
3. What is the simplest way to check a variable's value during debugging?
4. Why should you use const instead of let when the variable's value won't change?
Hands-on tasks in the game
- Code editor
Create an array species with the species 'T-Rex', 'Velociraptor' and 'Triceratops'. Add 'Stegosaurus' to the end with push(), remove the first element with shift() and store it in a constant called removed. Display the species array and its length in the console.
- Click in order
Arrange the elements of a template literal with interpolation:
- Code editor
Store as BigInt: const dinoEraStart = 245000000n (the start of the dinosaur era in years ago) and const dinoEraEnd = 66000000n (its end). Calculate dinoEraDuration as the difference dinoEraStart - dinoEraEnd, and dinoEraDays as dinoEraDuration multiplied by 365n. Display both results in the console.
- Horizontal ordering
Arrange the elements of checking a variable's type:
- Code editor
Create a constant species holding a dinosaur species name as text, e.g. 'Tyrannosaurus Rex', and a variable age (let) with the age 25. After the birthday change age to 26 and display species and age in the console.
- Vertical ordering
Arrange the places where JavaScript looks for a variable (scope chain):
- Horizontal ordering
Arrange the elements of an arrow function declaration:
- Code editor
Write a function ageInMillions(years) that returns the age of a fossil in millions of years, rounded to a whole number with Math.round(). Call it for a fossil that is 66000000 years old and display the result in the console.
- Click in order
Arrange the memory allocation process for variables:
- Vertical ordering
Arrange the steps of checking a variable's type in production code:
- Vertical ordering
Arrange the introduction of new JavaScript data types chronologically:
- Click in order
Arrange the elements of an array declaration in JavaScript
- Vertical ordering
Arrange the memory management stages for variables in JavaScript:
- Horizontal ordering
Arrange the elements of adding an item to an array:
Tasks after this lesson
- Coding taskWorking with Arrays
- Click in orderSorting: Template Literal
- QuestionArray Basics - pop() Method
- Coding taskBigInt Calculations
- Put in ordertypeof Syntax
- Coding taskExercise: Create a Variable Storing a Dinosaur Species
- Put in orderVariable Scope Resolution
- Put in orderArrow Function Syntax
- Questiontypeof Operator
- Coding taskExercise: Write a Function to Calculate Fossil Age
- Click in orderMemory Allocation Process
- Put in orderType Checking Flow
- Put in orderEvolution of Types in JavaScript
- Click in orderArray Basics - Declaration Syntax
- Put in orderMemory Management Cycle
- QuestionDebugging Variable Issues
- Put in orderArray Basics - push() Method Syntax
- QuestionVariable Optimization