JavaScript Intermediate

JavaScript Arrays: Working with Lists of Data

CodingerWeb
CodingerWeb
18 views 60 min read

Understanding Arrays

Arrays are ordered lists that can store multiple values. They're one of the most important data structures in JavaScript.

Creating Arrays

// Array literal (most common)
let fruits = ["apple", "banana", "orange"];
let numbers = [1, 2, 3, 4, 5];
let mixed = ["hello", 42, true, null];

// Array constructor
let colors = new Array("red", "green", "blue");

// Empty array
let empty = [];

console.log(fruits);   // ["apple", "banana", "orange"]
console.log(fruits.length);  // 3

Accessing Array Elements

let animals = ["cat", "dog", "bird", "fish"];

// Access by index (starts at 0)
console.log(animals[0]);  // "cat"
console.log(animals[2]);  // "bird"

// Last element
console.log(animals[animals.length - 1]);  // "fish"

// Modify elements
animals[1] = "puppy";
console.log(animals);  // ["cat", "puppy", "bird", "fish"]

Adding and Removing Elements

let cities = ["New York", "London"];

// Add to end
cities.push("Tokyo");
cities.push("Paris", "Sydney");
console.log(cities);  // ["New York", "London", "Tokyo", "Paris", "Sydney"]

// Remove from end
let lastCity = cities.pop();
console.log(lastCity);  // "Sydney"
console.log(cities);    // ["New York", "London", "Tokyo", "Paris"]

// Add to beginning
cities.unshift("Berlin");
console.log(cities);  // ["Berlin", "New York", "London", "Tokyo", "Paris"]

// Remove from beginning
let firstCity = cities.shift();
console.log(firstCity);  // "Berlin"
console.log(cities);     // ["New York", "London", "Tokyo", "Paris"]

Array Methods for Searching

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

// indexOf - find index of element
console.log(numbers.indexOf(30));    // 2
console.log(numbers.indexOf(100));   // -1 (not found)

// includes - check if element exists
console.log(numbers.includes(40));   // true
console.log(numbers.includes(60));   // false

// find - find first element that matches condition
let found = numbers.find(num => num > 25);
console.log(found);  // 30

// findIndex - find index of first element that matches
let foundIndex = numbers.findIndex(num => num > 25);
console.log(foundIndex);  // 2

Array Methods for Transformation

let numbers = [1, 2, 3, 4, 5];

// map - transform each element
let doubled = numbers.map(num => num * 2);
console.log(doubled);  // [2, 4, 6, 8, 10]

// filter - keep elements that match condition
let evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers);  // [2, 4]

// reduce - combine all elements into single value
let sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum);  // 15

// forEach - execute function for each element
numbers.forEach((num, index) => {
    console.log(`Index ${index}: ${num}`);
});

Array Methods for Manipulation

let letters = ["a", "b", "c", "d", "e"];

// slice - extract portion (doesn't modify original)
let portion = letters.slice(1, 4);
console.log(portion);  // ["b", "c", "d"]
console.log(letters);  // ["a", "b", "c", "d", "e"] (unchanged)

// splice - remove/add elements (modifies original)
let removed = letters.splice(2, 2, "x", "y");
console.log(removed);  // ["c", "d"]
console.log(letters);  // ["a", "b", "x", "y", "e"]

// concat - combine arrays
let moreLetters = ["f", "g"];
let combined = letters.concat(moreLetters);
console.log(combined);  // ["a", "b", "x", "y", "e", "f", "g"]

// join - convert to string
let joined = letters.join("-");
console.log(joined);  // "a-b-x-y-e"

Sorting Arrays

let fruits = ["banana", "apple", "orange", "grape"];
let numbers = [3, 1, 4, 1, 5, 9, 2, 6];

// sort - alphabetical (modifies original)
fruits.sort();
console.log(fruits);  // ["apple", "banana", "grape", "orange"]

// sort numbers (need custom compare function)
numbers.sort((a, b) => a - b);  // ascending
console.log(numbers);  // [1, 1, 2, 3, 4, 5, 6, 9]

numbers.sort((a, b) => b - a);  // descending
console.log(numbers);  // [9, 6, 5, 4, 3, 2, 1, 1]

// reverse
fruits.reverse();
console.log(fruits);  // ["orange", "grape", "banana", "apple"]

Multi-dimensional Arrays

// Array of arrays
let matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

console.log(matrix[1][2]);  // 6 (row 1, column 2)

// Iterate through 2D array
for (let i = 0; i < matrix.length; i++) {
    for (let j = 0; j < matrix[i].length; j++) {
        console.log(`matrix[${i}][${j}] = ${matrix[i][j]}`);
    }
}

Practice Exercises

// Exercise 1: Student grades
let grades = [85, 92, 78, 96, 87];

let average = grades.reduce((sum, grade) => sum + grade, 0) / grades.length;
let highest = Math.max(...grades);
let lowest = Math.min(...grades);
let passing = grades.filter(grade => grade >= 70);

console.log(`Average: ${average.toFixed(1)}`);
console.log(`Highest: ${highest}`);
console.log(`Lowest: ${lowest}`);
console.log(`Passing grades: ${passing.length}/${grades.length}`);

// Exercise 2: Shopping cart
let cart = [
    { name: "Laptop", price: 999.99, quantity: 1 },
    { name: "Mouse", price: 29.99, quantity: 2 },
    { name: "Keyboard", price: 79.99, quantity: 1 }
];

let total = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
let itemCount = cart.reduce((count, item) => count + item.quantity, 0);

console.log(`Total items: ${itemCount}`);
console.log(`Total cost: $${total.toFixed(2)}`);

// Exercise 3: Text analysis
let words = ["javascript", "is", "awesome", "and", "powerful"];

let longWords = words.filter(word => word.length > 5);
let capitalizedWords = words.map(word => word.charAt(0).toUpperCase() + word.slice(1));
let totalLetters = words.reduce((count, word) => count + word.length, 0);

console.log("Long words:", longWords);
console.log("Capitalized:", capitalizedWords);
console.log("Total letters:", totalLetters);