We use cookies to enhance your experience on the site
CodeWorlds

Creating and Manipulating Arrays in JavaScript

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

[]
:

1// Array of dinosaur species in our park
2const dinosaurs = ["Tyrannosaurus", "Velociraptor", "Triceratops", "Brachiosaurus"];
3
4// Array of mixed data types (numbers, strings, booleans)
5const dinoData = ["Blue", 5, true, 120.5];
6
7// Empty array, to which we will add elements later
8const dinoEnclosures = [];

2. Array Constructor

We can also use the

Array()
constructor:

1// Array created using the constructor
2const parkSectors = new Array("A", "B", "C", "D", "E");
3
4// Array with a predefined length but no values
5const securityReadings = new Array(10); // Creates an array with 10 empty elements
6
7// Note: if we pass only one number, it creates an array of that length
8// If we pass multiple arguments, they become elements of the array
9const confusingArray = new Array(3); // Array of length 3: [empty x 3]
10const 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():

1// Always creates an array with the passed elements
2const weights = Array.of(5000); // [5000], not an array of length 5000
3const 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):

1// Creating an array from an iterable (string)
2const dinoLetters = Array.from("TREX"); // ["T", "R", "E", "X"]
3
4// Creating an array with mapping
5const dinoAges = Array.from([5, 7, 3, 10], age => age * 2); // [10, 14, 6, 20]
6
7// Example with DOM collection (in browser)
8// 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.

1const velociraptors = ["Blue", "Delta", "Echo", "Charlie"];
2
3// Accessing individual elements
4console.log(velociraptors[0]); // "Blue"
5console.log(velociraptors[2]); // "Echo"
6
7// Modifying an element
8velociraptors[1] = "New Delta";
9console.log(velociraptors); // ["Blue", "New Delta", "Echo", "Charlie"]
10
11// Accessing a non-existent element returns undefined
12console.log(velociraptors[10]); // undefined

Array Length

The

length
property returns the number of elements in the array:

1const dinosaurs = ["T-Rex", "Velociraptor", "Triceratops"];
2console.log(dinosaurs.length); // 3
3
4// We can also modify the array length
5dinosaurs.length = 2;
6console.log(dinosaurs); // ["T-Rex", "Velociraptor"] - Triceratops was removed
7
8// Increasing the length adds empty elements
9dinosaurs.length = 5;
10console.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()

1const dinosaurs = ["T-Rex", "Velociraptor"];
2
3// Adding to the end
4dinosaurs.push("Triceratops");
5console.log(dinosaurs); // ["T-Rex", "Velociraptor", "Triceratops"]
6
7// push can add multiple elements at once
8dinosaurs.push("Brachiosaurus", "Stegosaurus");
9console.log(dinosaurs); // ["T-Rex", "Velociraptor", "Triceratops", "Brachiosaurus", "Stegosaurus"]
10
11// push returns the new length of the array
12const newLength = dinosaurs.push("Ankylosaurus");
13console.log(newLength); // 6

2. At the Beginning of the Array: unshift()

1const dinosaurs = ["Velociraptor", "Triceratops"];
2
3// Adding to the beginning
4dinosaurs.unshift("T-Rex");
5console.log(dinosaurs); // ["T-Rex", "Velociraptor", "Triceratops"]
6
7// unshift can also add multiple elements at once
8dinosaurs.unshift("Spinosaurus", "Dilophosaurus");
9console.log(dinosaurs); // ["Spinosaurus", "Dilophosaurus", "T-Rex", "Velociraptor", "Triceratops"]
10
11// unshift also returns the new length of the array
12const newLength = dinosaurs.unshift("Compsognathus");
13console.log(newLength); // 6

3. At a Specific Position: splice()

1const dinosaurs = ["T-Rex", "Velociraptor", "Stegosaurus"];
2
3// Inserting an element at position 1 (as the second element)
4// splice(position, howManyToRemove, elementsToAdd...)
5dinosaurs.splice(1, 0, "Triceratops");
6console.log(dinosaurs); // ["T-Rex", "Triceratops", "Velociraptor", "Stegosaurus"]
7
8// Replacing the element at position 2
9dinosaurs.splice(2, 1, "Brachiosaurus");
10console.log(dinosaurs); // ["T-Rex", "Triceratops", "Brachiosaurus", "Stegosaurus"]
11
12// We can add multiple elements at once
13dinosaurs.splice(1, 0, "Ankylosaurus", "Dilophosaurus");
14console.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()

1const dinosaurs = ["T-Rex", "Velociraptor", "Triceratops"];
2
3// Removing the last element
4const removedDino = dinosaurs.pop();
5console.log(removedDino); // "Triceratops"
6console.log(dinosaurs); // ["T-Rex", "Velociraptor"]

2. From the Beginning of the Array: shift()

1const dinosaurs = ["T-Rex", "Velociraptor", "Triceratops"];
2
3// Removing the first element
4const removedDino = dinosaurs.shift();
5console.log(removedDino); // "T-Rex"
6console.log(dinosaurs); // ["Velociraptor", "Triceratops"]

3. From a Specific Position: splice()

1const dinosaurs = ["T-Rex", "Velociraptor", "Triceratops", "Stegosaurus"];
2
3// Removing one element at position 1
4const removedDinos = dinosaurs.splice(1, 1);
5console.log(removedDinos); // ["Velociraptor"]
6console.log(dinosaurs); // ["T-Rex", "Triceratops", "Stegosaurus"]
7
8// Removing multiple elements starting from position 1
9const moreRemovedDinos = dinosaurs.splice(1, 2);
10console.log(moreRemovedDinos); // ["Triceratops", "Stegosaurus"]
11console.log(dinosaurs); // ["T-Rex"]

Finding Elements in an Array

1. indexOf() and lastIndexOf()

1const dinosaurs = ["T-Rex", "Velociraptor", "Triceratops", "Velociraptor"];
2
3// Finding the first occurrence
4const firstIndex = dinosaurs.indexOf("Velociraptor");
5console.log(firstIndex); // 1
6
7// Finding the last occurrence
8const lastIndex = dinosaurs.lastIndexOf("Velociraptor");
9console.log(lastIndex); // 3
10
11// If the element doesn't exist, returns -1
12const notFoundIndex = dinosaurs.indexOf("Spinosaurus");
13console.log(notFoundIndex); // -1

2. includes() (ES6)

1const dinosaurs = ["T-Rex", "Velociraptor", "Triceratops"];
2
3// Check if an element exists in the array
4const hasVelociraptor = dinosaurs.includes("Velociraptor");
5console.log(hasVelociraptor); // true
6
7const hasSpinosaurus = dinosaurs.includes("Spinosaurus");
8console.log(hasSpinosaurus); // false

3. find() and findIndex() (ES6)

These methods are useful for searching complex elements (objects) based on criteria:

1// Array of dinosaur objects
2const dinosaurData = [
3  { name: "Rex", species: "Tyrannosaurus", age: 16, dangerous: true },
4  { name: "Blue", species: "Velociraptor", age: 5, dangerous: true },
5  { name: "Spike", species: "Stegosaurus", age: 10, dangerous: false },
6  { name: "Trixie", species: "Triceratops", age: 18, dangerous: false }
7];
8
9// Find the first dinosaur older than 15
10const oldDino = dinosaurData.find(dino => dino.age > 15);
11console.log(oldDino); // { name: "Rex", species: "Tyrannosaurus", age: 16, dangerous: true }
12
13// Find the index of the first safe dinosaur
14const safeIndex = dinosaurData.findIndex(dino => !dino.dangerous);
15console.log(safeIndex); // 2 (Spike)

Copying and Merging Arrays

1. Copying an Array with slice()

1const originalDinos = ["T-Rex", "Velociraptor", "Triceratops"];
2
3// Creating a copy of the entire array
4const dinosCopy = originalDinos.slice();
5console.log(dinosCopy); // ["T-Rex", "Velociraptor", "Triceratops"]
6
7// Copying part of the array (from index 1 to the end)
8const partialCopy = originalDinos.slice(1);
9console.log(partialCopy); // ["Velociraptor", "Triceratops"]
10
11// Copying a range (from index 0 to 1, not including 2)
12const rangeCopy = originalDinos.slice(0, 2);
13console.log(rangeCopy); // ["T-Rex", "Velociraptor"]

2. Merging Arrays with concat()

1const carnivores = ["T-Rex", "Velociraptor"];
2const herbivores = ["Triceratops", "Brachiosaurus", "Stegosaurus"];
3
4// Merging two arrays
5const allDinos = carnivores.concat(herbivores);
6console.log(allDinos);
7// ["T-Rex", "Velociraptor", "Triceratops", "Brachiosaurus", "Stegosaurus"]
8
9// You can merge multiple arrays at once
10const smallDinos = ["Compsognathus"];
11const allSpecies = carnivores.concat(herbivores, smallDinos);
12console.log(allSpecies);
13// ["T-Rex", "Velociraptor", "Triceratops", "Brachiosaurus", "Stegosaurus", "Compsognathus"]

3. Spread Operator (ES6)

1const carnivores = ["T-Rex", "Velociraptor"];
2const herbivores = ["Triceratops", "Brachiosaurus"];
3
4// Merging arrays with spread
5const allDinos = [...carnivores, ...herbivores];
6console.log(allDinos); // ["T-Rex", "Velociraptor", "Triceratops", "Brachiosaurus"]
7
8// You can add elements in the middle
9const mixedCollection = [...carnivores, "Dilophosaurus", ...herbivores];
10console.log(mixedCollection);
11// ["T-Rex", "Velociraptor", "Dilophosaurus", "Triceratops", "Brachiosaurus"]
12
13// Copying an array with spread
14const dinosCopy = [...carnivores];
15console.log(dinosCopy); // ["T-Rex", "Velociraptor"]

Searching and Sorting Arrays

1. Sorting an Array: sort()

1const dinosaurs = ["Velociraptor", "Tyrannosaurus", "Brachiosaurus", "Ankylosaurus"];
2
3// Alphabetical sort (default)
4dinosaurs.sort();
5console.log(dinosaurs);
6// ["Ankylosaurus", "Brachiosaurus", "Tyrannosaurus", "Velociraptor"]
7
8// Sorting numbers (requires a compare function)
9const dinoWeights = [5000, 500, 15000, 7000];
10
11// Default sort treats numbers as strings - this won't work correctly!
12dinoWeights.sort();
13console.log(dinoWeights); // [15000, 500, 5000, 7000] (incorrect!)
14
15// With a compare function - correct ascending sort
16dinoWeights.sort((a, b) => a - b);
17console.log(dinoWeights); // [500, 5000, 7000, 15000]
18
19// Descending sort
20dinoWeights.sort((a, b) => b - a);
21console.log(dinoWeights); // [15000, 7000, 5000, 500]

2. Sorting Objects

1const dinosaurData = [
2  { name: "Rex", species: "Tyrannosaurus", age: 16 },
3  { name: "Blue", species: "Velociraptor", age: 5 },
4  { name: "Spike", species: "Stegosaurus", age: 10 },
5  { name: "Trixie", species: "Triceratops", age: 18 }
6];
7
8// Sort by age (ascending)
9dinosaurData.sort((a, b) => a.age - b.age);
10console.log(dinosaurData.map(dino => `${dino.name} (${dino.age})`));
11// ["Blue (5)", "Spike (10)", "Rex (16)", "Trixie (18)"]
12
13// Sort by name (alphabetically)
14dinosaurData.sort((a, b) => a.name.localeCompare(b.name));
15console.log(dinosaurData.map(dino => dino.name));
16// ["Blue", "Rex", "Spike", "Trixie"]

3. Reversing Order: reverse()

1const dinosaurs = ["T-Rex", "Velociraptor", "Triceratops", "Brachiosaurus"];
2
3// Reverse the order of elements
4dinosaurs.reverse();
5console.log(dinosaurs); // ["Brachiosaurus", "Triceratops", "Velociraptor", "T-Rex"]

Transforming Arrays

1. Converting to String: join()

1const dinosaurs = ["T-Rex", "Velociraptor", "Triceratops"];
2
3// Joining all elements into a string with default separator (comma)
4const dinoString = dinosaurs.join();
5console.log(dinoString); // "T-Rex,Velociraptor,Triceratops"
6
7// With a custom separator
8const dinoList = dinosaurs.join(" | ");
9console.log(dinoList); // "T-Rex | Velociraptor | Triceratops"
10
11// Without a separator
12const dinoNoSeparator = dinosaurs.join("");
13console.log(dinoNoSeparator); // "T-RexVelociraptorTriceratops"

2. Converting String to Array: split()

1const dinoString = "T-Rex,Velociraptor,Triceratops";
2
3// Splitting a string into an array
4const dinosaurs = dinoString.split(",");
5console.log(dinosaurs); // ["T-Rex", "Velociraptor", "Triceratops"]
6
7// Splitting by each character
8const letters = "TREX".split("");
9console.log(letters); // ["T", "R", "E", "X"]

Practical Examples of Working with Arrays

Example 1: Dinosaur Inventory System

1// Dinosaur inventory system for Jurassic Park
2const dinosaurInventory = {
3  species: [],
4
5  // Adding a new species to the inventory
6  addSpecies: function(name, count, carnivore) {
7    // Check if the species already exists
8    const existingIndex = this.species.findIndex(s => s.name === name);
9
10    if (existingIndex >= 0) {
11      // Update existing species
12      this.species[existingIndex].count += count;
13      console.log(`Updated population of ${name}: ${this.species[existingIndex].count}`);
14    } else {
15      // Add new species
16      this.species.push({
17        name,
18        count,
19        carnivore,
20        addDate: new Date().toISOString().split('T')[0]
21      });
22      console.log(`Added new species: ${name} (specimen count: ${count})`);
23    }
24
25    return this;
26  },
27
28  // Removing dinosaurs (e.g., due to death or transfer)
29  removeSpecimens: function(name, count, reason) {
30    const index = this.species.findIndex(s => s.name === name);
31
32    if (index === -1) {
33      console.log(`Species ${name} does not exist in the inventory.`);
34      return false;
35    }
36
37    if (this.species[index].count < count) {
38      console.log(`Error: Trying to remove more specimens (${count}) than exist (${this.species[index].count}).`);
39      return false;
40    }
41
42    this.species[index].count -= count;
43    console.log(`Removed ${count} specimens of species ${name}. Reason: ${reason}.`);
44    console.log(`Remaining: ${this.species[index].count} specimens.`);
45
46    // If there are no more specimens, remove the species from the inventory
47    if (this.species[index].count === 0) {
48      const removed = this.species.splice(index, 1)[0];
49      console.log(`Species ${removed.name} has been completely removed from the inventory.`);
50    }
51
52    return true;
53  },
54
55  // Generate inventory summary
56  generateSummary: function() {
57    console.log("=== DINOSAUR INVENTORY SUMMARY ===");
58
59    if (this.species.length === 0) {
60      console.log("No dinosaurs in the inventory.");
61      return;
62    }
63
64    // Sort species by population (descending)
65    const sortedSpecies = [...this.species].sort((a, b) => b.count - a.count);
66
67    // Number of species and specimens
68    const totalSpecies = sortedSpecies.length;
69    const totalSpecimens = sortedSpecies.reduce((sum, species) => sum + species.count, 0);
70    console.log(`Number of species: ${totalSpecies}`);
71    console.log(`Total number of specimens: ${totalSpecimens}`);
72
73    // Split into carnivores and herbivores
74    const carnivores = sortedSpecies.filter(s => s.carnivore);
75    const herbivores = sortedSpecies.filter(s => !s.carnivore);
76
77    console.log(`Carnivore species: ${carnivores.length}`);
78    console.log(`Herbivore species: ${herbivores.length}`);
79
80    // Most numerous species
81    if (sortedSpecies.length > 0) {
82      console.log("\nLargest populations:");
83      sortedSpecies.slice(0, 3).forEach((species, i) => {
84        console.log(`${i+1}. ${species.name}: ${species.count} specimens`);
85      });
86    }
87
88    // Table of all species
89    console.log("\nDetailed species list:");
90    console.log("Name   | Population | Type        | Date Added");
91    console.log("-------|------------|-------------|-------------");
92    sortedSpecies.forEach(species => {
93      const type = species.carnivore ? "Carnivore" : "Herbivore";
94      console.log(`${species.name.padEnd(6)} | ${String(species.count).padEnd(10)} | ${type.padEnd(11)} | ${species.addDate}`);
95    });
96  }
97};
98
99// Testing the inventory system
100dinosaurInventory.addSpecies("T-Rex", 3, true);
101dinosaurInventory.addSpecies("Velociraptor", 12, true);
102dinosaurInventory.addSpecies("Triceratops", 8, false);
103dinosaurInventory.addSpecies("Brachiosaurus", 5, false);
104dinosaurInventory.addSpecies("Gallimimus", 20, false);
105
106// Updating existing species
107dinosaurInventory.addSpecies("Velociraptor", 4, true); // Adding 4 new Velociraptors
108
109// Removing specimens
110dinosaurInventory.removeSpecimens("T-Rex", 1, "Death from old age");
111dinosaurInventory.removeSpecimens("Gallimimus", 5, "Transfer to another park");
112
113// Generating the summary
114dinosaurInventory.generateSummary();

Example 2: Genetic Data Analysis

1// Simplified genetic data as an array
2const geneticData = [
3  { id: "TRX01", species: "Tyrannosaurus", sequenceMatch: 0.85, viability: "High", complete: true },
4  { id: "VLR02", species: "Velociraptor", sequenceMatch: 0.93, viability: "Medium", complete: true },
5  { id: "TRC04", species: "Triceratops", sequenceMatch: 0.79, viability: "Low", complete: false },
6  { id: "BRCH1", species: "Brachiosaurus", sequenceMatch: 0.81, viability: "Medium", complete: true },
7  { id: "STEG7", species: "Stegosaurus", sequenceMatch: 0.76, viability: "Low", complete: false },
8  { id: "ANKL5", species: "Ankylosaurus", sequenceMatch: 0.88, viability: "High", complete: true },
9  { id: "DILO3", species: "Dilophosaurus", sequenceMatch: 0.91, viability: "Medium", complete: false },
10  { id: "PTRD9", species: "Pteranodon", sequenceMatch: 0.72, viability: "Low", complete: false }
11];
12
13// Data analysis functions
14function analyzeGeneticData(data) {
15  console.log("=== GENETIC DATA ANALYSIS ===");
16
17  // 1. How many sequences are complete?
18  const completeSequences = data.filter(seq => seq.complete);
19  console.log(`Complete sequences: ${completeSequences.length} of ${data.length} (${((completeSequences.length / data.length) * 100).toFixed(1)}%)`);
20
21  // 2. Average sequence match coefficient
22  const averageMatch = data.reduce((sum, seq) => sum + seq.sequenceMatch, 0) / data.length;
23  console.log(`Average sequence match: ${(averageMatch * 100).toFixed(1)}%`);
24
25  // 3. Extract best and worst matches
26  const sortedByMatch = [...data].sort((a, b) => b.sequenceMatch - a.sequenceMatch);
27
28  console.log("\nBest sequence matches:");
29  sortedByMatch.slice(0, 3).forEach((seq, i) => {
30    console.log(`${i+1}. ${seq.species} (ID: ${seq.id}): ${(seq.sequenceMatch * 100).toFixed(1)}%`);
31  });
32
33  console.log("\nWorst sequence matches:");
34  sortedByMatch.slice(-3).reverse().forEach((seq, i) => {
35    console.log(`${i+1}. ${seq.species} (ID: ${seq.id}): ${(seq.sequenceMatch * 100).toFixed(1)}%`);
36  });
37
38  // 4. Group by viability
39  const viabilityGroups = data.reduce((groups, seq) => {
40    if (!groups[seq.viability]) {
41      groups[seq.viability] = [];
42    }
43    groups[seq.viability].push(seq);
44    return groups;
45  }, {});
46
47  console.log("\nGrouping by viability:");
48  Object.entries(viabilityGroups).forEach(([viability, sequences]) => {
49    console.log(`${viability}: ${sequences.length} sequences`);
50    sequences.forEach(seq => {
51      console.log(`  - ${seq.species} (ID: ${seq.id})`);
52    });
53  });
54
55  // 5. Priority sequences for further research
56  const highPrioritySequences = data.filter(seq =>
57    seq.sequenceMatch > 0.85 && !seq.complete
58  );
59
60  console.log("\nPriority sequences to complete:");
61  if (highPrioritySequences.length > 0) {
62    highPrioritySequences.forEach(seq => {
63      console.log(`- ${seq.species} (ID: ${seq.id}): match ${(seq.sequenceMatch * 100).toFixed(1)}%, viability: ${seq.viability}`);
64    });
65  } else {
66    console.log("No priority sequences.");
67  }
68
69  return {
70    totalSequences: data.length,
71    completeSequences: completeSequences.length,
72    averageMatch,
73    bestMatch: sortedByMatch[0],
74    worstMatch: sortedByMatch[sortedByMatch.length - 1],
75    viabilityDistribution: Object.fromEntries(
76      Object.entries(viabilityGroups).map(([key, val]) => [key, val.length])
77    ),
78    highPrioritySequences
79  };
80}
81
82// Execute analysis
83const analysisResults = analyzeGeneticData(geneticData);
84console.log("\nAnalysis result as object:", analysisResults);
85
86// Data filtering and manipulation
87console.log("\n=== DATA MANIPULATION ===");
88
89// 1. Create a new array with only selected fields
90const simplifiedData = geneticData.map(seq => ({
91  id: seq.id,
92  species: seq.species,
93  match: seq.sequenceMatch
94}));
95console.log("Simplified data:", simplifiedData);
96
97// 2. Filter to show only complete sequences with high match
98const highQualitySequences = geneticData.filter(seq =>
99  seq.complete && seq.sequenceMatch > 0.8
100);
101console.log("High quality sequences:", highQualitySequences);
102
103// 3. Sort alphabetically by species
104const sortedBySpecies = [...geneticData].sort((a, b) =>
105  a.species.localeCompare(b.species)
106);
107console.log("Sorted alphabetically by species:",
108  sortedBySpecies.map(seq => seq.species)
109);
110
111// 4. Merge with another array (new data)
112const newGeneticData = [
113  { id: "PCHY1", species: "Pachycephalosaurus", sequenceMatch: 0.83, viability: "Medium", complete: true },
114  { id: "SPNO5", species: "Spinosaurus", sequenceMatch: 0.89, viability: "High", complete: false }
115];
116
117const combinedData = [...geneticData, ...newGeneticData];
118console.log(`Combined data: ${combinedData.length} sequences`);
119
120// 5. Join into a CSV report string
121const csvHeader = "ID,Species,Match,Viability,Complete";
122const csvRows = combinedData.map(seq =>
123  `${seq.id},${seq.species},${seq.sequenceMatch},${seq.viability},${seq.complete}`
124);
125const csvReport = [csvHeader, ...csvRows].join('\n');
126console.log("CSV Report:");
127console.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:

1const dinosaurs = [
2  { name: "Rex", species: "Tyrannosaurus" },
3  { name: "Blue", species: "Velociraptor" },
4  { name: "Spike", species: "Stegosaurus" }
5];
6
7// Get only names
8const names = dinosaurs.map(dino => dino.name);
9console.log(names); // ["Rex", "Blue", "Spike"]
10
11// Create new objects
12const dinoLabels = dinosaurs.map(dino => ({
13  label: `${dino.name} (${dino.species})`,
14  id: dino.name.toLowerCase()
15}));
16console.log(dinoLabels);
17// [
18//   { label: "Rex (Tyrannosaurus)", id: "rex" },
19//   { label: "Blue (Velociraptor)", id: "blue" },
20//   { label: "Spike (Stegosaurus)", id: "spike" }
21// ]

2. filter() - Filtering Elements

The

filter()
method creates a new array containing only elements that meet a specified criterion:

1const dinosaurs = [
2  { name: "Rex", species: "Tyrannosaurus", carnivore: true, weight: 7000 },
3  { name: "Blue", species: "Velociraptor", carnivore: true, weight: 100 },
4  { name: "Spike", species: "Stegosaurus", carnivore: false, weight: 5000 },
5  { name: "Trixie", species: "Triceratops", carnivore: false, weight: 8000 }
6];
7
8// Filter only predators
9const carnivores = dinosaurs.filter(dino => dino.carnivore);
10console.log(carnivores.map(dino => dino.name)); // ["Rex", "Blue"]
11
12// Filter heavy dinosaurs
13const heavyDinos = dinosaurs.filter(dino => dino.weight > 1000);
14console.log(heavyDinos.map(dino => dino.name)); // ["Rex", "Spike", "Trixie"]
15
16// Combining conditions
17const heavyCarnivores = dinosaurs.filter(dino => dino.carnivore && dino.weight > 1000);
18console.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:

1const dinosaurs = [
2  { name: "Rex", species: "Tyrannosaurus", weight: 7000 },
3  { name: "Blue", species: "Velociraptor", weight: 100 },
4  { name: "Spike", species: "Stegosaurus", weight: 5000 },
5  { name: "Trixie", species: "Triceratops", weight: 8000 }
6];
7
8// Calculating total weight
9const totalWeight = dinosaurs.reduce((sum, dino) => sum + dino.weight, 0);
10console.log(`Total weight of dinosaurs: ${totalWeight} kg`); // 20100 kg
11
12// Finding the heaviest dinosaur
13const heaviestDino = dinosaurs.reduce(
14  (heaviest, dino) => dino.weight > heaviest.weight ? dino : heaviest,
15  dinosaurs[0]
16);
17console.log(`Heaviest dinosaur: ${heaviestDino.name} (${heaviestDino.weight} kg)`);
18// Heaviest dinosaur: Trixie (8000 kg)
19
20// Creating an object mapping species to dinosaurs
21const dinosBySpecies = dinosaurs.reduce((acc, dino) => {
22  acc[dino.species] = dino;
23  return acc;
24}, {});
25
26console.log(dinosBySpecies.Velociraptor.name); // "Blue"

4. some() and every() - Testing Elements

These methods check whether some/all elements meet a specified criterion:

1const dinosaurs = [
2  { name: "Rex", species: "Tyrannosaurus", dangerous: true, contained: true },
3  { name: "Blue", species: "Velociraptor", dangerous: true, contained: false },
4  { name: "Spike", species: "Stegosaurus", dangerous: false, contained: true }
5];
6
7// Check if any dinosaur is dangerous
8const anyDangerous = dinosaurs.some(dino => dino.dangerous);
9console.log("Is any dinosaur dangerous?", anyDangerous); // true
10
11// Check if all dinosaurs are safely contained
12const allContained = dinosaurs.every(dino => dino.contained);
13console.log("Are all dinosaurs safely contained?", allContained); // false
14
15// Check if all dangerous dinosaurs are contained
16const allDangerousContained = dinosaurs
17  .filter(dino => dino.dangerous)
18  .every(dino => dino.contained);
19console.log("Are all dangerous dinosaurs contained?", allDangerousContained); // false

5. flat() and flatMap() (ES2019)

These methods flatten nested arrays:

1// Nested array of dinosaurs by enclosure
2const enclosures = [
3  ["Rex", "Rexy"], // T-Rex enclosure
4  ["Blue", "Delta", "Echo"], // Velociraptor enclosure
5  ["Spike", "Spikey"], // Stegosaurus enclosure
6  [] // Empty enclosure
7];
8
9// Flatten to a single array
10const allDinos = enclosures.flat();
11console.log(allDinos); // ["Rex", "Rexy", "Blue", "Delta", "Echo", "Spike", "Spikey"]
12
13// More complex example with flatMap
14const enclosureData = [
15  { type: "T-Rex", dinosaurs: ["Rex", "Rexy"] },
16  { type: "Velociraptor", dinosaurs: ["Blue", "Delta", "Echo"] },
17  { type: "Stegosaurus", dinosaurs: ["Spike", "Spikey"] }
18];
19
20// Map and flatten in one step
21const dinosaursWithTypes = enclosureData.flatMap(enclosure =>
22  enclosure.dinosaurs.map(dino => `${dino} (${enclosure.type})`)
23);
24
25console.log(dinosaursWithTypes);
26// [
27//   "Rex (T-Rex)",
28//   "Rexy (T-Rex)",
29//   "Blue (Velociraptor)",
30//   "Delta (Velociraptor)",
31//   "Echo (Velociraptor)",
32//   "Spike (Stegosaurus)",
33//   "Spikey (Stegosaurus)"
34// ]

Summary

Arrays are one of the most powerful data structures in JavaScript, allowing you to store, organize, and manipulate collections of elements. In this module we learned:

  1. Different ways to create arrays: array literals, Array() constructor, Array.of() and Array.from() methods
  2. Basic array operations: adding elements (push, unshift, splice), removing elements (pop, shift, splice), accessing elements
  3. Search methods: indexOf, includes, find, findIndex
  4. Copy and merge methods: slice, concat, spread operator (...)
  5. Sorting and comparison methods: sort, reverse
  6. Transformation methods: join (to string), split (from string)
  7. 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 module, we will look at array methods that allow iterating over their elements and performing operations on each one.

Go to CodeWorlds