← Back to Hub

📊 Arrays & Array Methods

Master JavaScript's most powerful data structure

🎯 What You'll Learn

  • Creating and accessing arrays
  • Array methods (map, filter, reduce)
  • Adding/removing elements
  • Searching and sorting
  • Array iteration techniques
  • Multi-dimensional arrays

📚 Core Concepts

1. Creating Arrays

// Array literal (most common) let fruits = ["apple", "banana", "orange"]; let numbers = [1, 2, 3, 4, 5]; let mixed = ["text", 42, true, null]; // Array constructor let colors = new Array("red", "green", "blue"); // Empty array let empty = []; // Accessing elements (zero-indexed!) console.log(fruits[0]); // "apple" console.log(fruits[1]); // "banana" console.log(fruits[2]); // "orange" // Array length console.log(fruits.length); // 3 // Last element console.log(fruits[fruits.length - 1]); // "orange"
✏️ Try it: Create an array of your 5 favorite movies and print the first and last one.

2. Adding & Removing Elements

let numbers = [1, 2, 3]; // Add to end numbers.push(4); // [1, 2, 3, 4] numbers.push(5, 6); // [1, 2, 3, 4, 5, 6] // Remove from end let last = numbers.pop(); // Returns 6, array is [1, 2, 3, 4, 5] // Add to beginning numbers.unshift(0); // [0, 1, 2, 3, 4, 5] // Remove from beginning let first = numbers.shift(); // Returns 0, array is [1, 2, 3, 4, 5] // Add/remove from middle (splice) let arr = [1, 2, 3, 4, 5]; arr.splice(2, 1); // Remove 1 element at index 2: [1, 2, 4, 5] arr.splice(2, 0, 3); // Add 3 at index 2: [1, 2, 3, 4, 5] arr.splice(1, 2, 'x', 'y'); // Replace 2 elements: [1, 'x', 'y', 4, 5]

3. Essential Array Methods

map() - Transform every element
let nums = [1, 2, 3]; let doubled = nums.map(n => n * 2); // [2, 4, 6]
filter() - Keep elements that pass test
let nums = [1, 2, 3, 4, 5]; let evens = nums.filter(n => n % 2 === 0); // [2, 4]
find() - Get first matching element
let users = [{id: 1}, {id: 2}]; let user = users.find(u => u.id === 2); // {id: 2}
includes() - Check if element exists
let fruits = ["apple", "banana"]; fruits.includes("apple"); // true fruits.includes("grape"); // false

4. The Powerful reduce()

Reduce an array to a single value

// Sum all numbers let numbers = [1, 2, 3, 4, 5]; let sum = numbers.reduce((total, num) => total + num, 0); // 15 // Count occurrences let fruits = ["apple", "banana", "apple", "orange", "banana", "apple"]; let count = fruits.reduce((acc, fruit) => { acc[fruit] = (acc[fruit] || 0) + 1; return acc; }, {}); // {apple: 3, banana: 2, orange: 1} // Find max number let max = numbers.reduce((max, num) => num > max ? num : max, numbers[0]); // 5
💡 Tip: reduce() takes two parameters: a callback function and an initial value. The callback gets (accumulator, currentValue).

5. Sorting & Searching

// Sort strings let fruits = ["banana", "apple", "orange"]; fruits.sort(); // ["apple", "banana", "orange"] // Sort numbers (IMPORTANT: need compare function!) let nums = [10, 5, 40, 25, 1000]; nums.sort((a, b) => a - b); // [5, 10, 25, 40, 1000] ascending nums.sort((a, b) => b - a); // [1000, 40, 25, 10, 5] descending // Reverse nums.reverse(); // Reverse the array // indexOf & lastIndexOf let arr = [1, 2, 3, 2, 1]; arr.indexOf(2); // 1 (first occurrence) arr.lastIndexOf(2); // 3 (last occurrence) arr.indexOf(99); // -1 (not found)

6. Array Iteration

let fruits = ["apple", "banana", "orange"]; // forEach - do something with each element fruits.forEach((fruit, index) => { console.log(`${index}: ${fruit}`); }); // for...of - modern loop for (let fruit of fruits) { console.log(fruit); } // Classic for loop for (let i = 0; i < fruits.length; i++) { console.log(fruits[i]); } // some() - check if ANY element passes test let hasLongName = fruits.some(fruit => fruit.length > 6); // true // every() - check if ALL elements pass test let allShort = fruits.every(fruit => fruit.length < 10); // true

🛠️ Practice Projects

Project 1: Shopping Cart

Build a shopping cart system using arrays

Features to add:
  • Array of products with name, price, quantity
  • Add items to cart
  • Remove items from cart
  • Calculate total price using reduce()
  • Filter items by price range
  • Sort items by price or name

Project 2: Student Grade Manager

Manage student data and calculate statistics

Features to add:
  • Array of students with name and grades
  • Calculate average grade per student
  • Find highest and lowest scores
  • Filter students passing (>60)
  • Sort students by average grade
  • Display class statistics

Project 3: Todo List App

Classic todo app with array manipulation

Features to add:
  • Add new todos to array
  • Mark todos as complete/incomplete
  • Delete todos
  • Filter by status (all/active/completed)
  • Search todos by keyword
  • Count total/completed todos