Week 6: Mastering Arrays - Your First Collection

Learn how to organize, access, and manipulate collections of data using arrays in JavaScript.

Explore Chapter 6

Chapter 6: Organizing Data with Arrays

Introduction to Arrays: Creating, Accessing Elements.

Arrays are fundamental data structures in JavaScript used to store ordered collections of items. They are similar to lists in Python. Each item in an array has a specific position (index), starting from 0.

Creating Arrays

The most common way to create an array is using array literal syntax [].

// Empty array
let emptyArray = [];

// Array of numbers
let numbers = [10, 20, 30, 40, 50];

// Array of strings
let colors = ["red", "green", "blue"];

// Array of mixed data types
let mixedArray = [1, "hello", true, null, { name: "Alice" }]; // Arrays can hold different types

You can also create arrays using the new Array() constructor, but array literals are generally preferred.

Accessing Elements (Indexing)

You access array elements using their index within square brackets []. Remember that indices start at 0.

let fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]); // Output: "apple" (first element)
console.log(fruits[1]); // Output: "banana" (second element)

let thirdFruit = fruits[2]; // "cherry"
console.log(thirdFruit);

// Accessing an index that doesn't exist returns 'undefined'
console.log(fruits[3]); // Output: undefined

Array Length

The length property tells you how many elements are in the array.

console.log(fruits.length); // Output: 3

The length is always one more than the highest index.

Array Indexing and Modification.

Array indexing allows you to retrieve and also modify individual elements in an array, as arrays are mutable (changeable).

Accessing

As shown before, use array[index].

let scores = [85, 92, 78, 99];
let firstScore = scores[0]; // 85
let lastScore = scores[scores.length - 1]; // 99 (using length)
console.log("First:", firstScore, "Last:", lastScore);

Modifying Elements

You can change the value of an element by assigning a new value to its index.

let colors = ["red", "green", "blue"];
console.log("Original:", colors); // ["red", "green", "blue"]

colors[1] = "yellow"; // Change the element at index 1
console.log("Modified:", colors); // ["red", "yellow", "blue"]

Adding Elements (by index)

You can technically add elements by assigning to an index beyond the current length, but this can create "sparse" arrays (with empty slots) and is often less clear than using array methods like push.

colors[3] = "purple"; // Adds 'purple' at index 3
console.log("Added:", colors);    // ["red", "yellow", "blue", "purple"]
console.log("New length:", colors.length); // 4

colors[5] = "orange"; // Assigns to index 5, index 4 will be 'empty'
console.log("Sparse:", colors);   // ["red", "yellow", "blue", "purple", empty, "orange"]
console.log("Length:", colors.length); // 6
console.log(colors[4]); // undefined

Common Array Methods: Modifying and Manipulating Arrays.

JavaScript arrays come with a rich set of built-in methods for adding, removing, and manipulating elements.

Adding/Removing Elements:

  • push(element1, ..., elementN): Adds one or more elements to the end of the array and returns the new length. (Modifies original array).
    let pets = ["dog", "cat"];
    let newLength = pets.push("hamster", "goldfish");
    console.log(pets); // ["dog", "cat", "hamster", "goldfish"]
    console.log(newLength); // 4
  • pop(): Removes the last element from the array and returns that element. (Modifies original array).
    let lastPet = pets.pop();
    console.log(pets); // ["dog", "cat", "hamster"]
    console.log(lastPet); // "goldfish"
  • unshift(element1, ..., elementN): Adds one or more elements to the beginning of the array and returns the new length. (Modifies original array).
    pets.unshift("rabbit");
    console.log(pets); // ["rabbit", "dog", "cat", "hamster"]
  • shift(): Removes the first element from the array and returns that element. (Modifies original array).
    let firstPet = pets.shift();
    console.log(pets); // ["dog", "cat", "hamster"]
    console.log(firstPet); // "rabbit"

Slicing and Splicing:

  • slice(startIndex, endIndex): Returns a new array containing a shallow copy of a portion of the original array from startIndex (inclusive) up to endIndex (exclusive). Does not modify the original array.
    let numbers = [10, 20, 30, 40, 50, 60];
    let middleNums = numbers.slice(2, 5); // Start at index 2, end before index 5
    console.log(middleNums); // [30, 40, 50]
    console.log(numbers);    // [10, 20, 30, 40, 50, 60] (original unchanged)
    
    let endNums = numbers.slice(3); // From index 3 to the end
    console.log(endNums); // [40, 50, 60]
    
  • splice(startIndex, deleteCount, item1, ..., itemN): Changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. Returns an array containing the deleted elements. (Modifies original array).
    let letters = ['a', 'b', 'c', 'd', 'e'];
    
    // Remove 2 elements starting from index 1
    let removed = letters.splice(1, 2);
    console.log(letters); // ['a', 'd', 'e']
    console.log(removed); // ['b', 'c']
    
    // Remove 1 element at index 1, and insert 'X', 'Y'
    letters.splice(1, 1, 'X', 'Y');
    console.log(letters); // ['a', 'X', 'Y', 'e']
    
    // Insert 'Z' at index 2 without removing anything
    letters.splice(2, 0, 'Z');
    console.log(letters); // ['a', 'X', 'Z', 'Y', 'e']
    

Other Useful Methods:

  • indexOf(searchElement, fromIndex) / lastIndexOf(): Returns the first (or last) index at which a given element can be found, or -1 if not present.
  • includes(searchElement, fromIndex): Returns true if an array includes a certain value, false otherwise.
  • join(separator): Joins all elements of an array into a string, separated by the specified separator (default is comma).
  • reverse(): Reverses the order of elements in the array in place.
  • sort(): Sorts the elements of an array in place. (Default sort is often lexicographical/string-based, requires a compare function for numerical sort).

Array Iteration Methods.

JavaScript provides powerful methods specifically designed for iterating over arrays and performing actions on their elements, often replacing the need for manual for loops.

  • forEach(callbackFunction): Executes a provided callbackFunction once for each array element. Does not return a value.
    let names = ["Alice", "Bob", "Charlie"];
    
    names.forEach(function(name, index) {
      console.log(`Index ${index}: ${name}`);
    });
    
    // Using arrow function syntax:
    names.forEach((name) => console.log(`Hello, ${name}!`));
  • map(callbackFunction): Creates a new array populated with the results of calling a provided callbackFunction on every element in the calling array. Ideal for transforming data.
    let numbers = [1, 2, 3, 4];
    let squares = numbers.map(function(num) {
      return num * num;
    });
    console.log(squares); // [1, 4, 9, 16]
    console.log(numbers); // [1, 2, 3, 4] (original unchanged)
    
    // Using arrow function:
    let doubled = numbers.map(num => num * 2);
    console.log(doubled); // [2, 4, 6, 8]
    
  • filter(callbackFunction): Creates a new array with all elements that pass the test implemented by the provided callbackFunction (the callback should return true or false).
    let values = [10, -5, 25, 0, 18, -2];
    let positiveValues = values.filter(function(val) {
      return val > 0;
    });
    console.log(positiveValues); // [10, 25, 18]
    console.log(values);         // Original unchanged
    
    // Using arrow function:
    let evenValues = values.filter(val => val % 2 === 0);
    console.log(evenValues); // [10, 0, 18, -2]
    
  • Many others like reduce(), find(), findIndex(), some(), every() provide powerful ways to process array data.

These iteration methods often lead to more concise and readable code compared to traditional for loops for common array operations.

Syllabus