JavaScript and TypeScript course ยท Module 2: Functions, Arrays and Objects
Creating and Manipulating Arrays in JavaScript
In this lesson9
Welcome back to Jurassic Park! Today we will be working with arrays in JavaScript - data structures that are essential for managing collections of objects, such as our dinosaur species, genetic research results, or data from park monitoring systems.
What Are Arrays?
Arrays are ordered collections of elements that can store data of any type. You can compare them to laboratory cabinets where each drawer (array index) contains a specific sample (array element). Each element has its own unique position number (index), which starts from 0.
Creating Arrays
In JavaScript, there are several ways to create arrays:
1. Array Literal (Most Common)
The most popular way is to use square brackets []:
// Array of dinosaur species in our park
const dinosaurs = ["Tyrannosaurus", "Velociraptor", "Triceratops", "Brachiosaurus"];
// Array of mixed data types (numbers, strings, booleans)
const dinoData = ["Blue", 5, true, 120.5];
// Empty array, to which we will add elements later
const dinoEnclosures = [];2. Array Constructor
We can also use the Array() constructor:
// Array created using the constructor
const parkSectors = new Array("A", "B", "C", "D", "E");
// Array with a predefined length but no values
const securityReadings = new Array(10); // Creates an array with 10 empty elements
// Note: if we pass only one number, it creates an array of that length
// If we pass multiple arguments, they become elements of the array
const confusingArray = new Array(3); // Array of length 3: [empty x 3]
const normalArray = new Array(1, 2, 3); // Array with three elements: [1, 2, 3]3. Array.of() Method (ES6)
To avoid the ambiguity of the Array() constructor, you can use Array.of():
// Always creates an array with the passed elements
const weights = Array.of(5000); // [5000], not an array of length 5000
const measurements = Array.of(1, 2, 3, 4, 5); // [1, 2, 3, 4, 5]4. Array.from() Method (ES6)
This method creates an array from array-like objects (e.g., DOM collections) or iterables (e.g., strings):
// Creating an array from an iterable (string)
const dinoLetters = Array.from("TREX"); // ["T", "R", "E", "X"]
// Creating an array with mapping
const dinoAges = Array.from([5, 7, 3, 10], age => age * 2); // [10, 14, 6, 20]
// Example with DOM collection (in browser)
// const dinoElements = Array.from(document.querySelectorAll('.dinosaur'));Accessing Array Elements
Array elements are indexed from 0, meaning the first element has index 0, the second has index 1, and so on.
const velociraptors = ["Blue", "Delta", "Echo", "Charlie"];
// Accessing individual elements
console.log(velociraptors[0]); // "Blue"
console.log(velociraptors[2]); // "Echo"
// Modifying an element
velociraptors[1] = "New Delta";
console.log(velociraptors); // ["Blue", "New Delta", "Echo", "Charlie"]
// Accessing a non-existent element returns undefined
console.log(velociraptors[10]); // undefinedArray Length
The length property returns the number of elements in the array:
const dinosaurs = ["T-Rex", "Velociraptor", "Triceratops"];
console.log(dinosaurs.length); // 3
// We can also modify the array length
dinosaurs.length = 2;
console.log(dinosaurs); // ["T-Rex", "Velociraptor"] - Triceratops was removed
// Increasing the length adds empty elements
dinosaurs.length = 5;
console.log(dinosaurs); // ["T-Rex", "Velociraptor", empty x 3]Basic Array Operations
Adding Elements
There are several ways to add elements to an array:
1. At the End of the Array: push()
const dinosaurs = ["T-Rex", "Velociraptor"];
// Adding to the end
dinosaurs.push("Triceratops");
console.log(dinosaurs); // ["T-Rex", "Velociraptor", "Triceratops"]
// push can add multiple elements at once
dinosaurs.push("Brachiosaurus", "Stegosaurus");
console.log(dinosaurs); // ["T-Rex", "Velociraptor", "Triceratops", "Brachiosaurus", "Stegosaurus"]
// push returns the new length of the array
const newLength = dinosaurs.push("Ankylosaurus");
console.log(newLength); // 62. At the Beginning of the Array: unshift()
const dinosaurs = ["Velociraptor", "Triceratops"];
// Adding to the beginning
dinosaurs.unshift("T-Rex");
console.log(dinosaurs); // ["T-Rex", "Velociraptor", "Triceratops"]
// unshift can also add multiple elements at once
dinosaurs.unshift("Spinosaurus", "Dilophosaurus");
console.log(dinosaurs); // ["Spinosaurus", "Dilophosaurus", "T-Rex", "Velociraptor", "Triceratops"]
// unshift also returns the new length of the array
const newLength = dinosaurs.unshift("Compsognathus");
console.log(newLength); // 63. At a Specific Position: splice()
const dinosaurs = ["T-Rex", "Velociraptor", "Stegosaurus"];
// Inserting an element at position 1 (as the second element)
// splice(position, howManyToRemove, elementsToAdd...)
dinosaurs.splice(1, 0, "Triceratops");
console.log(dinosaurs); // ["T-Rex", "Triceratops", "Velociraptor", "Stegosaurus"]
// Replacing the element at position 2
dinosaurs.splice(2, 1, "Brachiosaurus");
console.log(dinosaurs); // ["T-Rex", "Triceratops", "Brachiosaurus", "Stegosaurus"]
// We can add multiple elements at once
dinosaurs.splice(1, 0, "Ankylosaurus", "Dilophosaurus");
console.log(dinosaurs); // ["T-Rex", "Ankylosaurus", "Dilophosaurus", "Triceratops", "Brachiosaurus", "Stegosaurus"]Removing Elements
Similar to adding, there are several methods for removing elements:
1. From the End of the Array: pop()
const dinosaurs = ["T-Rex", "Velociraptor", "Triceratops"];
// Removing the last element
const removedDino = dinosaurs.pop();
console.log(removedDino); // "Triceratops"
console.log(dinosaurs); // ["T-Rex", "Velociraptor"]2. From the Beginning of the Array: shift()
const dinosaurs = ["T-Rex", "Velociraptor", "Triceratops"];
// Removing the first element
const removedDino = dinosaurs.shift();
console.log(removedDino); // "T-Rex"
console.log(dinosaurs); // ["Velociraptor", "Triceratops"]3. From a Specific Position: splice()
const dinosaurs = ["T-Rex", "Velociraptor", "Triceratops", "Stegosaurus"];
// Removing one element at position 1
const removedDinos = dinosaurs.splice(1, 1);
console.log(removedDinos); // ["Velociraptor"]
console.log(dinosaurs); // ["T-Rex", "Triceratops", "Stegosaurus"]
// Removing multiple elements starting from position 1
const moreRemovedDinos = dinosaurs.splice(1, 2);
console.log(moreRemovedDinos); // ["Triceratops", "Stegosaurus"]
console.log(dinosaurs); // ["T-Rex"]Finding Elements in an Array
1. indexOf() and lastIndexOf()
const dinosaurs = ["T-Rex", "Velociraptor", "Triceratops", "Velociraptor"];
// Finding the first occurrence
const firstIndex = dinosaurs.indexOf("Velociraptor");
console.log(firstIndex); // 1
// Finding the last occurrence
const lastIndex = dinosaurs.lastIndexOf("Velociraptor");
console.log(lastIndex); // 3
// If the element doesn't exist, returns -1
const notFoundIndex = dinosaurs.indexOf("Spinosaurus");
console.log(notFoundIndex); // -12. includes() (ES6)
const dinosaurs = ["T-Rex", "Velociraptor", "Triceratops"];
// Check if an element exists in the array
const hasVelociraptor = dinosaurs.includes("Velociraptor");
console.log(hasVelociraptor); // true
const hasSpinosaurus = dinosaurs.includes("Spinosaurus");
console.log(hasSpinosaurus); // false3. find() and findIndex() (ES6)
These methods are useful for searching complex elements (objects) based on criteria:
// Array of dinosaur objects
const dinosaurData = [
{ name: "Rex", species: "Tyrannosaurus", age: 16, dangerous: true },
{ name: "Blue", species: "Velociraptor", age: 5, dangerous: true },
{ name: "Spike", species: "Stegosaurus", age: 10, dangerous: false },
{ name: "Trixie", species: "Triceratops", age: 18, dangerous: false }
];
// Find the first dinosaur older than 15
const oldDino = dinosaurData.find(dino => dino.age > 15);
console.log(oldDino); // { name: "Rex", species: "Tyrannosaurus", age: 16, dangerous: true }
// Find the index of the first safe dinosaur
const safeIndex = dinosaurData.findIndex(dino => !dino.dangerous);
console.log(safeIndex); // 2 (Spike)Copying and Merging Arrays
1. Copying an Array with slice()
const originalDinos = ["T-Rex", "Velociraptor", "Triceratops"];
// Creating a copy of the entire array
const dinosCopy = originalDinos.slice();
console.log(dinosCopy); // ["T-Rex", "Velociraptor", "Triceratops"]
// Copying part of the array (from index 1 to the end)
const partialCopy = originalDinos.slice(1);
console.log(partialCopy); // ["Velociraptor", "Triceratops"]
// Copying a range (from index 0 to 1, not including 2)
const rangeCopy = originalDinos.slice(0, 2);
console.log(rangeCopy); // ["T-Rex", "Velociraptor"]2. Merging Arrays with concat()
const carnivores = ["T-Rex", "Velociraptor"];
const herbivores = ["Triceratops", "Brachiosaurus", "Stegosaurus"];
// Merging two arrays
const allDinos = carnivores.concat(herbivores);
console.log(allDinos);
// ["T-Rex", "Velociraptor", "Triceratops", "Brachiosaurus", "Stegosaurus"]
// You can merge multiple arrays at once
const smallDinos = ["Compsognathus"];
const allSpecies = carnivores.concat(herbivores, smallDinos);
console.log(allSpecies);
// ["T-Rex", "Velociraptor", "Triceratops", "Brachiosaurus", "Stegosaurus", "Compsognathus"]3. Spread Operator (ES6)
const carnivores = ["T-Rex", "Velociraptor"];
const herbivores = ["Triceratops", "Brachiosaurus"];
// Merging arrays with spread
const allDinos = [...carnivores, ...herbivores];
console.log(allDinos); // ["T-Rex", "Velociraptor", "Triceratops", "Brachiosaurus"]
// You can add elements in the middle
const mixedCollection = [...carnivores, "Dilophosaurus", ...herbivores];
console.log(mixedCollection);
// ["T-Rex", "Velociraptor", "Dilophosaurus", "Triceratops", "Brachiosaurus"]
// Copying an array with spread
const dinosCopy = [...carnivores];
console.log(dinosCopy); // ["T-Rex", "Velociraptor"]Searching and Sorting Arrays
1. Sorting an Array: sort()
const dinosaurs = ["Velociraptor", "Tyrannosaurus", "Brachiosaurus", "Ankylosaurus"];
// Alphabetical sort (default)
dinosaurs.sort();
console.log(dinosaurs);
// ["Ankylosaurus", "Brachiosaurus", "Tyrannosaurus", "Velociraptor"]
// Sorting numbers (requires a compare function)
const dinoWeights = [5000, 500, 15000, 7000];
// Default sort treats numbers as strings - this won't work correctly!
dinoWeights.sort();
console.log(dinoWeights); // [15000, 500, 5000, 7000] (incorrect!)
// With a compare function - correct ascending sort
dinoWeights.sort((a, b) => a - b);
console.log(dinoWeights); // [500, 5000, 7000, 15000]
// Descending sort
dinoWeights.sort((a, b) => b - a);
console.log(dinoWeights); // [15000, 7000, 5000, 500]2. Sorting Objects
const dinosaurData = [
{ name: "Rex", species: "Tyrannosaurus", age: 16 },
{ name: "Blue", species: "Velociraptor", age: 5 },
{ name: "Spike", species: "Stegosaurus", age: 10 },
{ name: "Trixie", species: "Triceratops", age: 18 }
];
// Sort by age (ascending)
dinosaurData.sort((a, b) => a.age - b.age);
console.log(dinosaurData.map(dino => `${dino.name} (${dino.age})`));
// ["Blue (5)", "Spike (10)", "Rex (16)", "Trixie (18)"]
// Sort by name (alphabetically)
dinosaurData.sort((a, b) => a.name.localeCompare(b.name));
console.log(dinosaurData.map(dino => dino.name));
// ["Blue", "Rex", "Spike", "Trixie"]3. Reversing Order: reverse()
const dinosaurs = ["T-Rex", "Velociraptor", "Triceratops", "Brachiosaurus"];
// Reverse the order of elements
dinosaurs.reverse();
console.log(dinosaurs); // ["Brachiosaurus", "Triceratops", "Velociraptor", "T-Rex"]Transforming Arrays
1. Converting to String: join()
const dinosaurs = ["T-Rex", "Velociraptor", "Triceratops"];
// Joining all elements into a string with default separator (comma)
const dinoString = dinosaurs.join();
console.log(dinoString); // "T-Rex,Velociraptor,Triceratops"
// With a custom separator
const dinoList = dinosaurs.join(" | ");
console.log(dinoList); // "T-Rex | Velociraptor | Triceratops"
// Without a separator
const dinoNoSeparator = dinosaurs.join("");
console.log(dinoNoSeparator); // "T-RexVelociraptorTriceratops"2. Converting String to Array: split()
const dinoString = "T-Rex,Velociraptor,Triceratops";
// Splitting a string into an array
const dinosaurs = dinoString.split(",");
console.log(dinosaurs); // ["T-Rex", "Velociraptor", "Triceratops"]
// Splitting by each character
const letters = "TREX".split("");
console.log(letters); // ["T", "R", "E", "X"]Practical Examples of Working with Arrays
Example 1: Dinosaur Inventory System
// Dinosaur inventory system for Jurassic Park
const dinosaurInventory = {
species: [],
// Adding a new species to the inventory
addSpecies: function(name, count, carnivore) {
// Check if the species already exists
const existingIndex = this.species.findIndex(s => s.name === name);
if (existingIndex >= 0) {
// Update existing species
this.species[existingIndex].count += count;
console.log(`Updated population of ${name}: ${this.species[existingIndex].count}`);
} else {
// Add new species
this.species.push({
name,
count,
carnivore,
addDate: new Date().toISOString().split('T')[0]
});
console.log(`Added new species: ${name} (specimen count: ${count})`);
}
return this;
},
// Removing dinosaurs (e.g., due to death or transfer)
removeSpecimens: function(name, count, reason) {
const index = this.species.findIndex(s => s.name === name);
if (index === -1) {
console.log(`Species ${name} does not exist in the inventory.`);
return false;
}
if (this.species[index].count < count) {
console.log(`Error: Trying to remove more specimens (${count}) than exist (${this.species[index].count}).`);
return false;
}
this.species[index].count -= count;
console.log(`Removed ${count} specimens of species ${name}. Reason: ${reason}.`);
console.log(`Remaining: ${this.species[index].count} specimens.`);
// If there are no more specimens, remove the species from the inventory
if (this.species[index].count === 0) {
const removed = this.species.splice(index, 1)[0];
console.log(`Species ${removed.name} has been completely removed from the inventory.`);
}
return true;
},
// Generate inventory summary
generateSummary: function() {
console.log("=== DINOSAUR INVENTORY SUMMARY ===");
if (this.species.length === 0) {
console.log("No dinosaurs in the inventory.");
return;
}
// Sort species by population (descending)
const sortedSpecies = [...this.species].sort((a, b) => b.count - a.count);
// Number of species and specimens
const totalSpecies = sortedSpecies.length;
const totalSpecimens = sortedSpecies.reduce((sum, species) => sum + species.count, 0);
console.log(`Number of species: ${totalSpecies}`);
console.log(`Total number of specimens: ${totalSpecimens}`);
// Split into carnivores and herbivores
const carnivores = sortedSpecies.filter(s => s.carnivore);
const herbivores = sortedSpecies.filter(s => !s.carnivore);
console.log(`Carnivore species: ${carnivores.length}`);
console.log(`Herbivore species: ${herbivores.length}`);
// Most numerous species
if (sortedSpecies.length > 0) {
console.log("\nLargest populations:");
sortedSpecies.slice(0, 3).forEach((species, i) => {
console.log(`${i+1}. ${species.name}: ${species.count} specimens`);
});
}
// Table of all species
console.log("\nDetailed species list:");
console.log("Name | Population | Type | Date Added");
console.log("-------|------------|-------------|-------------");
sortedSpecies.forEach(species => {
const type = species.carnivore ? "Carnivore" : "Herbivore";
console.log(`${species.name.padEnd(6)} | ${String(species.count).padEnd(10)} | ${type.padEnd(11)} | ${species.addDate}`);
});
}
};
// Testing the inventory system
dinosaurInventory.addSpecies("T-Rex", 3, true);
dinosaurInventory.addSpecies("Velociraptor", 12, true);
dinosaurInventory.addSpecies("Triceratops", 8, false);
dinosaurInventory.addSpecies("Brachiosaurus", 5, false);
dinosaurInventory.addSpecies("Gallimimus", 20, false);
// Updating existing species
dinosaurInventory.addSpecies("Velociraptor", 4, true); // Adding 4 new Velociraptors
// Removing specimens
dinosaurInventory.removeSpecimens("T-Rex", 1, "Death from old age");
dinosaurInventory.removeSpecimens("Gallimimus", 5, "Transfer to another park");
// Generating the summary
dinosaurInventory.generateSummary();Example 2: Genetic Data Analysis
// Simplified genetic data as an array
const geneticData = [
{ id: "TRX01", species: "Tyrannosaurus", sequenceMatch: 0.85, viability: "High", complete: true },
{ id: "VLR02", species: "Velociraptor", sequenceMatch: 0.93, viability: "Medium", complete: true },
{ id: "TRC04", species: "Triceratops", sequenceMatch: 0.79, viability: "Low", complete: false },
{ id: "BRCH1", species: "Brachiosaurus", sequenceMatch: 0.81, viability: "Medium", complete: true },
{ id: "STEG7", species: "Stegosaurus", sequenceMatch: 0.76, viability: "Low", complete: false },
{ id: "ANKL5", species: "Ankylosaurus", sequenceMatch: 0.88, viability: "High", complete: true },
{ id: "DILO3", species: "Dilophosaurus", sequenceMatch: 0.91, viability: "Medium", complete: false },
{ id: "PTRD9", species: "Pteranodon", sequenceMatch: 0.72, viability: "Low", complete: false }
];
// Data analysis functions
function analyzeGeneticData(data) {
console.log("=== GENETIC DATA ANALYSIS ===");
// 1. How many sequences are complete?
const completeSequences = data.filter(seq => seq.complete);
console.log(`Complete sequences: ${completeSequences.length} of ${data.length} (${((completeSequences.length / data.length) * 100).toFixed(1)}%)`);
// 2. Average sequence match coefficient
const averageMatch = data.reduce((sum, seq) => sum + seq.sequenceMatch, 0) / data.length;
console.log(`Average sequence match: ${(averageMatch * 100).toFixed(1)}%`);
// 3. Extract best and worst matches
const sortedByMatch = [...data].sort((a, b) => b.sequenceMatch - a.sequenceMatch);
console.log("\nBest sequence matches:");
sortedByMatch.slice(0, 3).forEach((seq, i) => {
console.log(`${i+1}. ${seq.species} (ID: ${seq.id}): ${(seq.sequenceMatch * 100).toFixed(1)}%`);
});
console.log("\nWorst sequence matches:");
sortedByMatch.slice(-3).reverse().forEach((seq, i) => {
console.log(`${i+1}. ${seq.species} (ID: ${seq.id}): ${(seq.sequenceMatch * 100).toFixed(1)}%`);
});
// 4. Group by viability
const viabilityGroups = data.reduce((groups, seq) => {
if (!groups[seq.viability]) {
groups[seq.viability] = [];
}
groups[seq.viability].push(seq);
return groups;
}, {});
console.log("\nGrouping by viability:");
Object.entries(viabilityGroups).forEach(([viability, sequences]) => {
console.log(`${viability}: ${sequences.length} sequences`);
sequences.forEach(seq => {
console.log(` - ${seq.species} (ID: ${seq.id})`);
});
});
// 5. Priority sequences for further research
const highPrioritySequences = data.filter(seq =>
seq.sequenceMatch > 0.85 && !seq.complete
);
console.log("\nPriority sequences to complete:");
if (highPrioritySequences.length > 0) {
highPrioritySequences.forEach(seq => {
console.log(`- ${seq.species} (ID: ${seq.id}): match ${(seq.sequenceMatch * 100).toFixed(1)}%, viability: ${seq.viability}`);
});
} else {
console.log("No priority sequences.");
}
return {
totalSequences: data.length,
completeSequences: completeSequences.length,
averageMatch,
bestMatch: sortedByMatch[0],
worstMatch: sortedByMatch[sortedByMatch.length - 1],
viabilityDistribution: Object.fromEntries(
Object.entries(viabilityGroups).map(([key, val]) => [key, val.length])
),
highPrioritySequences
};
}
// Execute analysis
const analysisResults = analyzeGeneticData(geneticData);
console.log("\nAnalysis result as object:", analysisResults);
// Data filtering and manipulation
console.log("\n=== DATA MANIPULATION ===");
// 1. Create a new array with only selected fields
const simplifiedData = geneticData.map(seq => ({
id: seq.id,
species: seq.species,
match: seq.sequenceMatch
}));
console.log("Simplified data:", simplifiedData);
// 2. Filter to show only complete sequences with high match
const highQualitySequences = geneticData.filter(seq =>
seq.complete && seq.sequenceMatch > 0.8
);
console.log("High quality sequences:", highQualitySequences);
// 3. Sort alphabetically by species
const sortedBySpecies = [...geneticData].sort((a, b) =>
a.species.localeCompare(b.species)
);
console.log("Sorted alphabetically by species:",
sortedBySpecies.map(seq => seq.species)
);
// 4. Merge with another array (new data)
const newGeneticData = [
{ id: "PCHY1", species: "Pachycephalosaurus", sequenceMatch: 0.83, viability: "Medium", complete: true },
{ id: "SPNO5", species: "Spinosaurus", sequenceMatch: 0.89, viability: "High", complete: false }
];
const combinedData = [...geneticData, ...newGeneticData];
console.log(`Combined data: ${combinedData.length} sequences`);
// 5. Join into a CSV report string
const csvHeader = "ID,Species,Match,Viability,Complete";
const csvRows = combinedData.map(seq =>
`${seq.id},${seq.species},${seq.sequenceMatch},${seq.viability},${seq.complete}`
);
const csvReport = [csvHeader, ...csvRows].join('\n');
console.log("CSV Report:");
console.log(csvReport);Advanced Array Methods (ES6+)
Modern JavaScript provides many powerful methods for working with arrays that greatly simplify data processing.
1. map() - Transforming Elements
The map() method creates a new array by transforming each element of the original array:
const dinosaurs = [
{ name: "Rex", species: "Tyrannosaurus" },
{ name: "Blue", species: "Velociraptor" },
{ name: "Spike", species: "Stegosaurus" }
];
// Get only names
const names = dinosaurs.map(dino => dino.name);
console.log(names); // ["Rex", "Blue", "Spike"]
// Create new objects
const dinoLabels = dinosaurs.map(dino => ({
label: `${dino.name} (${dino.species})`,
id: dino.name.toLowerCase()
}));
console.log(dinoLabels);
// [
// { label: "Rex (Tyrannosaurus)", id: "rex" },
// { label: "Blue (Velociraptor)", id: "blue" },
// { label: "Spike (Stegosaurus)", id: "spike" }
// ]2. filter() - Filtering Elements
The filter() method creates a new array containing only elements that meet a specified criterion:
const dinosaurs = [
{ name: "Rex", species: "Tyrannosaurus", carnivore: true, weight: 7000 },
{ name: "Blue", species: "Velociraptor", carnivore: true, weight: 100 },
{ name: "Spike", species: "Stegosaurus", carnivore: false, weight: 5000 },
{ name: "Trixie", species: "Triceratops", carnivore: false, weight: 8000 }
];
// Filter only predators
const carnivores = dinosaurs.filter(dino => dino.carnivore);
console.log(carnivores.map(dino => dino.name)); // ["Rex", "Blue"]
// Filter heavy dinosaurs
const heavyDinos = dinosaurs.filter(dino => dino.weight > 1000);
console.log(heavyDinos.map(dino => dino.name)); // ["Rex", "Spike", "Trixie"]
// Combining conditions
const heavyCarnivores = dinosaurs.filter(dino => dino.carnivore && dino.weight > 1000);
console.log(heavyCarnivores.map(dino => dino.name)); // ["Rex"]3. reduce() - Aggregating Elements
The reduce() method reduces an array to a single value by processing all elements:
const dinosaurs = [
{ name: "Rex", species: "Tyrannosaurus", weight: 7000 },
{ name: "Blue", species: "Velociraptor", weight: 100 },
{ name: "Spike", species: "Stegosaurus", weight: 5000 },
{ name: "Trixie", species: "Triceratops", weight: 8000 }
];
// Calculating total weight
const totalWeight = dinosaurs.reduce((sum, dino) => sum + dino.weight, 0);
console.log(`Total weight of dinosaurs: ${totalWeight} kg`); // 20100 kg
// Finding the heaviest dinosaur
const heaviestDino = dinosaurs.reduce(
(heaviest, dino) => dino.weight > heaviest.weight ? dino : heaviest,
dinosaurs[0]
);
console.log(`Heaviest dinosaur: ${heaviestDino.name} (${heaviestDino.weight} kg)`);
// Heaviest dinosaur: Trixie (8000 kg)
// Creating an object mapping species to dinosaurs
const dinosBySpecies = dinosaurs.reduce((acc, dino) => {
acc[dino.species] = dino;
return acc;
}, {});
console.log(dinosBySpecies.Velociraptor.name); // "Blue"4. some() and every() - Testing Elements
These methods check whether some/all elements meet a specified criterion:
const dinosaurs = [
{ name: "Rex", species: "Tyrannosaurus", dangerous: true, contained: true },
{ name: "Blue", species: "Velociraptor", dangerous: true, contained: false },
{ name: "Spike", species: "Stegosaurus", dangerous: false, contained: true }
];
// Check if any dinosaur is dangerous
const anyDangerous = dinosaurs.some(dino => dino.dangerous);
console.log("Is any dinosaur dangerous?", anyDangerous); // true
// Check if all dinosaurs are safely contained
const allContained = dinosaurs.every(dino => dino.contained);
console.log("Are all dinosaurs safely contained?", allContained); // false
// Check if all dangerous dinosaurs are contained
const allDangerousContained = dinosaurs
.filter(dino => dino.dangerous)
.every(dino => dino.contained);
console.log("Are all dangerous dinosaurs contained?", allDangerousContained); // false5. flat() and flatMap() (ES2019)
These methods flatten nested arrays:
// Nested array of dinosaurs by enclosure
const enclosures = [
["Rex", "Rexy"], // T-Rex enclosure
["Blue", "Delta", "Echo"], // Velociraptor enclosure
["Spike", "Spikey"], // Stegosaurus enclosure
[] // Empty enclosure
];
// Flatten to a single array
const allDinos = enclosures.flat();
console.log(allDinos); // ["Rex", "Rexy", "Blue", "Delta", "Echo", "Spike", "Spikey"]
// More complex example with flatMap
const enclosureData = [
{ type: "T-Rex", dinosaurs: ["Rex", "Rexy"] },
{ type: "Velociraptor", dinosaurs: ["Blue", "Delta", "Echo"] },
{ type: "Stegosaurus", dinosaurs: ["Spike", "Spikey"] }
];
// Map and flatten in one step
const dinosaursWithTypes = enclosureData.flatMap(enclosure =>
enclosure.dinosaurs.map(dino => `${dino} (${enclosure.type})`)
);
console.log(dinosaursWithTypes);
// [
// "Rex (T-Rex)",
// "Rexy (T-Rex)",
// "Blue (Velociraptor)",
// "Delta (Velociraptor)",
// "Echo (Velociraptor)",
// "Spike (Stegosaurus)",
// "Spikey (Stegosaurus)"
// ]Summary
Arrays are one of the most powerful data structures in JavaScript, allowing you to store, organize, and manipulate collections of elements. In this lesson we learned:
- Different ways to create arrays: array literals, Array() constructor, Array.of() and Array.from() methods
- Basic array operations: adding elements (push, unshift, splice), removing elements (pop, shift, splice), accessing elements
- Search methods: indexOf, includes, find, findIndex
- Copy and merge methods: slice, concat, spread operator (...)
- Sorting and comparison methods: sort, reverse
- Transformation methods: join (to string), split (from string)
- Advanced processing methods: map, filter, reduce, some, every, flat, flatMap
The ability to effectively use arrays is essential in everyday work with JavaScript, especially when managing large datasets like our virtual dinosaur inventory.
In the next lesson, you will learn the methods that add and remove array elements.
Code for this lesson: index.js
// Arrays - Jurassic Park
console.log("JavaScript Array Laboratory");
console.log("Managing collections of dinosaurs\n");
// ===========================================
// 1. CREATING ARRAYS
// ===========================================
console.log("=== 1. Creating arrays ===");
// Way 1: Array literal (most common)
const dinosaurs = ["T-Rex", "Velociraptor", "Triceratops"];
console.log("Literal:", dinosaurs);
// Way 2: Array constructor
const carnivores = new Array("T-Rex", "Velociraptor", "Spinosaurus");
console.log("Constructor:", carnivores);
// Way 3: Array.of()
const herbivores = Array.of("Triceratops", "Stegosaurus", "Brachiosaurus");
console.log("Array.of():", herbivores);
// Way 4: Array.from()
const dinoNames = "TRex";
const lettersArray = Array.from(dinoNames);
console.log("Array.from():", lettersArray);
// Empty array
const emptyArray = [];
console.log("Empty:", emptyArray, "length:", emptyArray.length);
// Array of a specified size
const fixedSize = new Array(5);
console.log("Size 5:", fixedSize, "length:", fixedSize.length);
// ===========================================
// 2. ACCESSING ELEMENTS
// ===========================================
console.log("\n=== 2. Access to elements ===");
const jurassicDinos = ["T-Rex", "Velociraptor", "Triceratops", "Stegosaurus", "Brachiosaurus"];
console.log("\nAccess via index:");
console.log("First [0]:", jurassicDinos[0]);
console.log("Second [1]:", jurassicDinos[1]);
console.log("Last [-1 = length-1]:", jurassicDinos[jurassicDinos.length - 1]);
// Accessing a non-existent index
console.log("Non-existent [10]:", jurassicDinos[10]); // undefined
// Array length
console.log("\nArray length:", jurassicDinos.length);
// ===========================================
// 3. ADDING ELEMENTS
// ===========================================
console.log("\n=== 3. Adding elements ===");
const parkDinos = ["T-Rex", "Velociraptor"];
console.log("\nInitial list:", parkDinos);
// push() - add at the end
parkDinos.push("Triceratops");
console.log("push('Triceratops'):", parkDinos);
parkDinos.push("Stegosaurus", "Brachiosaurus");
console.log("push(2 elements):", parkDinos);
// unshift() - add at the beginning
parkDinos.unshift("Dilophosaurus");
console.log("unshift('Dilophosaurus'):", parkDinos);
// Direct assignment to an index
parkDinos[10] = "Pteranodon";
console.log("parkDinos[10]:", parkDinos);
console.log("Length:", parkDinos.length); // 11 (there are empty slots!)
// ===========================================
// 4. REMOVING ELEMENTS
// ===========================================
console.log("\n=== 4. Removing elements ===");
const removeDinos = ["T-Rex", "Velociraptor", "Triceratops", "Stegosaurus"];
console.log("\nInitial list:", removeDinos);
// pop() - removes the last one
const removed1 = removeDinos.pop();
console.log(`pop(): removed '${removed1}'`, removeDinos);
// shift() - removes the first one
const removed2 = removeDinos.shift();
console.log(`shift(): removed '${removed2}'`, removeDinos);
// delete - creates a "hole" (NOT RECOMMENDED!)
delete removeDinos[0];
console.log("delete removeDinos[0]:", removeDinos);
console.log("Length still:", removeDinos.length);
// splice() - removing from any position
const spliceDinos = ["T-Rex", "Velociraptor", "Triceratops", "Stegosaurus", "Brachiosaurus"];
const removed3 = spliceDinos.splice(2, 1); // Remove 1 element from index 2
console.log(`\nsplice(2, 1): removed ${removed3}`, spliceDinos);
// ===========================================
// 5. MODIFYING ELEMENTS
// ===========================================
console.log("\n=== 5. Modifying elements ===");
const modifyDinos = ["T-Rex", "Velociraptor", "Triceratops"];
console.log("\nOriginal:", modifyDinos);
// Changing a single element
modifyDinos[1] = "Blue (Velociraptor)";
console.log("After change [1]:", modifyDinos);
// splice() for replacing
modifyDinos.splice(2, 1, "Trike (Triceratops)", "Stego (Stegosaurus)");
console.log("splice(2, 1, ...2 new):", modifyDinos);
// ===========================================
// 6. COPYING ARRAYS
// ===========================================
console.log("\n=== 6. Copying arrays ===");
const original = ["T-Rex", "Velociraptor", "Triceratops"];
// Shallow copy - spread operator
const copy1 = [...original];
console.log("\nSpread [...original]:", copy1);
// Shallow copy - slice()
const copy2 = original.slice();
console.log("slice():", copy2);
// Shallow copy - Array.from()
const copy3 = Array.from(original);
console.log("Array.from():", copy3);
// Assignment (NOT a copy!)
const reference = original;
reference.push("Stegosaurus");
console.log("\nReference (NOT a copy):");
console.log("original:", original); // Also changed!
console.log("reference:", reference);
// ===========================================
// 7. COMBINING ARRAYS
// ===========================================
console.log("\n=== 7. Joining arrays ===");
const carnivoreList = ["T-Rex", "Velociraptor", "Spinosaurus"];
const herbivoreList = ["Triceratops", "Stegosaurus", "Brachiosaurus"];
// concat()
const allDinos1 = carnivoreList.concat(herbivoreList);
console.log("\nconcat():", allDinos1);
// Spread operator
const allDinos2 = [...carnivoreList, ...herbivoreList];
console.log("Spread:", allDinos2);
// Combining with additional elements
const allDinos3 = [...carnivoreList, "Dilophosaurus", ...herbivoreList];
console.log("Spread + additional:", allDinos3);
// ===========================================
// 8. SLICING AND SPLITTING
// ===========================================
console.log("\n=== 8. Slicing arrays ===");
const allSpecies = ["T-Rex", "Velociraptor", "Triceratops", "Stegosaurus", "Brachiosaurus"];
// slice(start, end) - does not modify the original
const firstThree = allSpecies.slice(0, 3);
console.log("\nslice(0, 3):", firstThree);
console.log("Original:", allSpecies); // Unchanged
const lastTwo = allSpecies.slice(-2);
console.log("slice(-2) - last 2:", lastTwo);
const middle = allSpecies.slice(1, 4);
console.log("slice(1, 4) - middle:", middle);
// splice(start, deleteCount, ...items) - modifies original
const splicedArray = ["T-Rex", "Velociraptor", "Triceratops", "Stegosaurus"];
const removedItems = splicedArray.splice(1, 2, "Blue", "Charlie");
console.log("\nsplice(1, 2, 'Blue', 'Charlie'):");
console.log("Removed:", removedItems);
console.log("Modified:", splicedArray);
// ===========================================
// 9. SEARCHING IN ARRAYS
// ===========================================
console.log("\n=== 9. Searching ===");
const searchDinos = ["T-Rex", "Velociraptor", "Triceratops", "Velociraptor", "Stegosaurus"];
// indexOf() - first index
console.log("\nindexOf('Velociraptor'):", searchDinos.indexOf("Velociraptor"));
console.log("indexOf('Brachiosaurus'):", searchDinos.indexOf("Brachiosaurus")); // -1 (not found)
// lastIndexOf() - last index
console.log("lastIndexOf('Velociraptor'):", searchDinos.lastIndexOf("Velociraptor"));
// includes() - checks whether it contains
console.log("\nincludes('T-Rex'):", searchDinos.includes("T-Rex"));
console.log("includes('Pteranodon'):", searchDinos.includes("Pteranodon"));
// find() - first element satisfying the condition
const longName = searchDinos.find(dino => dino.length > 10);
console.log("\nfind(dino => dino.length > 10):", longName);
// findIndex() - index of the first element
const longNameIndex = searchDinos.findIndex(dino => dino.length > 10);
console.log("findIndex(dino => dino.length > 10):", longNameIndex);
// ===========================================
// 10. REVERSING AND SORTING
// ===========================================
console.log("\n=== 10. Reversing and sorting ===");
const sortDinos = ["Triceratops", "Velociraptor", "Stegosaurus", "T-Rex", "Brachiosaurus"];
console.log("\nOriginal:", sortDinos);
// reverse() - reverses the order (modifies the original!)
const reversed = [...sortDinos].reverse(); // A copy, so the original is not changed
console.log("reverse():", reversed);
// sort() - sorts alphabetically (modifies the original!)
const sorted = [...sortDinos].sort();
console.log("sort():", sorted);
// Custom sorting
const weights = [8000, 80, 9000, 50000, 5000];
console.log("\nWeights:", weights);
const sortedWeights = [...weights].sort((a, b) => a - b);
console.log("sort() ascending:", sortedWeights);
const sortedDesc = [...weights].sort((a, b) => b - a);
console.log("sort() descending:", sortedDesc);
// ===========================================
// 11. COMPLEX EXAMPLE
// ===========================================
console.log("\n=== 11. Inventory system - complex example ===");
class DinosaurInventory {
constructor() {
this.dinosaurs = [];
}
add(name, species, sector, health = 100) {
const dino = { id: this.dinosaurs.length + 1, name, species, sector, health };
this.dinosaurs.push(dino);
console.log(`Added: ${name} (${species}) to sector ${sector}`);
}
remove(name) {
const index = this.dinosaurs.findIndex(d => d.name === name);
if (index !== -1) {
const removed = this.dinosaurs.splice(index, 1)[0];
console.log(`Removed: ${removed.name}`);
} else {
console.log(`Not found: ${name}`);
}
}
findBySector(sector) {
return this.dinosaurs.filter(d => d.sector === sector);
}
findBySpecies(species) {
return this.dinosaurs.filter(d => d.species === species);
}
getHealthy() {
return this.dinosaurs.filter(d => d.health >= 80);
}
getUnhealthy() {
return this.dinosaurs.filter(d => d.health < 80);
}
sortByName() {
return [...this.dinosaurs].sort((a, b) => a.name.localeCompare(b.name));
}
sortByHealth() {
return [...this.dinosaurs].sort((a, b) => b.health - a.health);
}
displayAll() {
console.log(`\nINVENTORY - Total: ${this.dinosaurs.length}`);
console.log("=".repeat(60));
this.dinosaurs.forEach((dino, i) => {
console.log(`${i + 1}. ${dino.name} (${dino.species}) - Sector ${dino.sector} - Health: ${dino.health}%`);
});
}
displayReport() {
console.log("\nDETAILED REPORT");
console.log("=".repeat(60));
const sectors = [...new Set(this.dinosaurs.map(d => d.sector))].sort();
sectors.forEach(sector => {
const inSector = this.findBySector(sector);
console.log(`\nSector ${sector} (${inSector.length} dinosaurs):`);
inSector.forEach(dino => {
console.log(` - ${dino.name} (${dino.species}) - ${dino.health}%`);
});
});
const healthy = this.getHealthy();
const unhealthy = this.getUnhealthy();
console.log(`\nHealthy (${healthy.length}): ${healthy.map(d => d.name).join(", ")}`);
if (unhealthy.length > 0) {
console.log(`Need attention (${unhealthy.length}): ${unhealthy.map(d => d.name).join(", ")}`);
}
}
}
// System demonstration
const inventory = new DinosaurInventory();
inventory.add("Rexy", "Tyrannosaurus Rex", "A", 95);
inventory.add("Blue", "Velociraptor", "B", 100);
inventory.add("Charlie", "Velociraptor", "B", 85);
inventory.add("Trike", "Triceratops", "C", 70);
inventory.add("Stego", "Stegosaurus", "C", 92);
inventory.add("Brachio", "Brachiosaurus", "D", 88);
inventory.displayAll();
inventory.displayReport();
console.log("\nSorting by name:");
inventory.sortByName().forEach((d, i) => {
console.log(` ${i + 1}. ${d.name}`);
});
console.log("\nSorting by health:");
inventory.sortByHealth().forEach((d, i) => {
console.log(` ${i + 1}. ${d.name} - ${d.health}%`);
});
inventory.remove("Charlie");
inventory.displayAll();
console.log("\nCongratulations! You've mastered arrays in JavaScript!");Docs entries used in this lesson
Spotted a mistake in this lesson?
Hands-on tasks in the game
- Vertical ordering
Arrange the steps of adding a new dinosaur species to an array in JavaScript: