03 - Arrays
What are Arrays?
Arrays store multiple values in a single variable. They're ordered collections where each item has an index (starting from 0).
const fruits = ["apple", "banana", "orange"];
console.log(fruits[0]); // "apple" — first item
console.log(fruits[1]); // "banana" — second item
console.log(fruits[2]); // "orange" — third item
console.log(fruits.length); // 3 — number of itemsCreating Arrays
// Array literal (most common)
const numbers = [1, 2, 3, 4, 5];
// Empty array
const empty = [];
// Mixed types (not recommended, but possible)
const mixed = [1, "hello", true, null];
// Array constructor (rarely used)
const arr = new Array(1, 2, 3);Adding and Removing Items
const fruits = ["apple", "banana"];
// Add to end
fruits.push("orange");
console.log(fruits); // ["apple", "banana", "orange"]
// Remove from end
const last = fruits.pop();
console.log(last); // "orange"
console.log(fruits); // ["apple", "banana"]
// Add to beginning
fruits.unshift("mango");
console.log(fruits); // ["mango", "apple", "banana"]
// Remove from beginning
const first = fruits.shift();
console.log(first); // "mango"
console.log(fruits); // ["apple", "banana"]Array Methods
Finding Items
const numbers = [1, 2, 3, 4, 5];
// includes — check if item exists
console.log(numbers.includes(3)); // true
console.log(numbers.includes(10)); // false
// indexOf — get index of item (-1 if not found)
console.log(numbers.indexOf(3)); // 2
console.log(numbers.indexOf(10)); // -1
// find — get first item matching condition
const found = numbers.find((num) => num > 3);
console.log(found); // 4
// findIndex — get index of first match
const index = numbers.findIndex((num) => num > 3);
console.log(index); // 3Transforming Arrays
const numbers = [1, 2, 3, 4, 5];
// map — transform each item
const doubled = numbers.map((num) => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
// filter — keep items matching condition
const evens = numbers.filter((num) => num % 2 === 0);
console.log(evens); // [2, 4]
// reduce — combine all items into single value
const sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // 15
// Real-world example — total price
const items = [
{ name: "Book", price: 10 },
{ name: "Pen", price: 2 },
{ name: "Notebook", price: 5 }
];
const total = items.reduce((sum, item) => sum + item.price, 0);
console.log(total); // 17Sorting and Reversing
const numbers = [3, 1, 4, 1, 5, 9];
// sort — mutates the original array
numbers.sort();
console.log(numbers); // [1, 1, 3, 4, 5, 9]
// Sort numbers correctly (default sorts as strings)
const nums = [10, 5, 40, 25];
nums.sort((a, b) => a - b); // ascending
console.log(nums); // [5, 10, 25, 40]
nums.sort((a, b) => b - a); // descending
console.log(nums); // [40, 25, 10, 5]
// reverse — mutates the original array
const letters = ["a", "b", "c"];
letters.reverse();
console.log(letters); // ["c", "b", "a"]Slicing and Splicing
const fruits = ["apple", "banana", "orange", "mango", "grape"];
// slice — copy a portion (doesn't modify original)
const some = fruits.slice(1, 3);
console.log(some); // ["banana", "orange"]
console.log(fruits); // unchanged
// slice — copy from index to end
const last = fruits.slice(2);
console.log(last); // ["orange", "mango", "grape"]
// splice — remove/add items (modifies original)
const removed = fruits.splice(1, 2); // remove 2 items starting at index 1
console.log(removed); // ["banana", "orange"]
console.log(fruits); // ["apple", "mango", "grape"]
// splice — add items
fruits.splice(1, 0, "kiwi", "pear"); // add at index 1, remove 0 items
console.log(fruits); // ["apple", "kiwi", "pear", "mango", "grape"]Iterating Over Arrays
const fruits = ["apple", "banana", "orange"];
// forEach — run function for each item
fruits.forEach((fruit) => {
console.log(fruit);
});
// forEach with index
fruits.forEach((fruit, index) => {
console.log(`${index}: ${fruit}`);
});
// for...of loop — modern and clean
for (const fruit of fruits) {
console.log(fruit);
}
// Traditional for loop — when you need the index
for (let i = 0; i < fruits.length; i++) {
console.log(`${i}: ${fruits[i]}`);
}Array Destructuring
Extract values from arrays into variables:
const colors = ["red", "green", "blue"];
// Old way
const first = colors[0];
const second = colors[1];
// Destructuring
const [first, second, third] = colors;
console.log(first); // "red"
console.log(second); // "green"
console.log(third); // "blue"
// Skip items
const [primary, , tertiary] = colors;
console.log(primary); // "red"
console.log(tertiary); // "blue"
// Rest operator
const numbers = [1, 2, 3, 4, 5];
const [first, second, ...rest] = numbers;
console.log(first); // 1
console.log(second); // 2
console.log(rest); // [3, 4, 5]Spread Operator
Expand arrays into individual elements:
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
// Combine arrays
const combined = [...arr1, ...arr2];
console.log(combined); // [1, 2, 3, 4, 5, 6]
// Copy array
const copy = [...arr1];
console.log(copy); // [1, 2, 3]
// Add items
const withExtra = [0, ...arr1, 4];
console.log(withExtra); // [0, 1, 2, 3, 4]
// Pass array items as function arguments
const numbers = [1, 2, 3];
console.log(Math.max(...numbers)); // 3Common Patterns
// Check if any item matches condition
const numbers = [1, 2, 3, 4, 5];
const hasEven = numbers.some((num) => num % 2 === 0);
console.log(hasEven); // true
// Check if all items match condition
const allPositive = numbers.every((num) => num > 0);
console.log(allPositive); // true
// Join array into string
const words = ["Hello", "World"];
console.log(words.join(" ")); // "Hello World"
console.log(words.join(", ")); // "Hello, World"
// Split string into array
const sentence = "Hello World";
const words = sentence.split(" ");
console.log(words); // ["Hello", "World"]
// Remove duplicates
const numbers = [1, 2, 2, 3, 3, 3, 4];
const unique = [...new Set(numbers)];
console.log(unique); // [1, 2, 3, 4]Key Takeaways
- Arrays are zero-indexed (first item is at index 0)
map,filter,reduceare powerful transformation methodsforEachandfor...ofare the modern ways to iterate- Spread operator (
...) copies and combines arrays - Destructuring extracts values into variables
- Most array methods don't modify the original (except
push,pop,shift,unshift,splice,sort,reverse)