Arrays & Array Methods
Checking access...
Arrays store ordered collections of data. They are the most commonly used data structure in JavaScript.
Creating Arrays
// Array literal (preferred)const fruits = ["apple", "banana", "cherry"];const numbers = [1, 2, 3, 4, 5];const mixed = ["hello", 42, true, null, { name: "Alice" }];
// Array constructor (avoid)const arr = new Array(3); // Creates array with 3 empty slotsAccessing and Modifying
const colors = ["red", "green", "blue"];
// Access by index (0-based)console.log(colors[0]); // => "red"console.log(colors[2]); // => "blue"console.log(colors[-1]); // => undefined (no negative indexing like Python)
// Lengthconsole.log(colors.length); // => 3
// Modifycolors[1] = "yellow";console.log(colors); // => ["red", "yellow", "blue"]
// Last elementconsole.log(colors[colors.length - 1]); // => "blue"Adding and Removing Elements
const items = ["a", "b", "c"];
// Enditems.push("d"); // Add to endconsole.log(items); // => ["a", "b", "c", "d"]const last = items.pop(); // Remove from endconsole.log(last); // => "d"console.log(items); // => ["a", "b", "c"]
// Beginningitems.unshift("z"); // Add to beginningconsole.log(items); // => ["z", "a", "b", "c"]const first = items.shift(); // Remove from beginningconsole.log(first); // => "z"console.log(items); // => ["a", "b", "c"]Finding Elements
const numbers = [10, 20, 30, 40, 50];
// indexOf — returns index or -1console.log(numbers.indexOf(30)); // => 2console.log(numbers.indexOf(99)); // => -1
// includes — booleanconsole.log(numbers.includes(30)); // => trueconsole.log(numbers.includes(99)); // => false
// find — returns first matching elementconst found = numbers.find(n => n > 25);console.log(found); // => 30
// findIndex — returns index of first matchconst index = numbers.findIndex(n => n > 25);console.log(index); // => 2
// some/every — boolean checksconsole.log(numbers.some(n => n > 40)); // => true (at least one)console.log(numbers.every(n => n > 5)); // => true (all)Slicing and Splicing
const arr = ["a", "b", "c", "d", "e"];
// slice — returns a new array (original unchanged)console.log(arr.slice(1, 3)); // => ["b", "c"] (start at 1, end before 3)console.log(arr.slice(2)); // => ["c", "d", "e"] (from 2 to end)console.log(arr.slice(-2)); // => ["d", "e"] (last 2)
// splice — modifies original array (add/remove at index)const arr2 = ["a", "b", "c", "d"];arr2.splice(1, 2); // Remove 2 elements starting at index 1console.log(arr2); // => ["a", "d"]
arr2.splice(1, 0, "x", "y"); // Insert at index 1 (remove 0)console.log(arr2); // => ["a", "x", "y", "d"]Iteration Methods (The Important Ones)
forEach — Execute for each element
const fruits = ["apple", "banana", "cherry"];
fruits.forEach((fruit, index) => { console.log(`${index}: ${fruit}`);});// 0: apple// 1: banana// 2: cherrymap — Transform each element (returns new array)
const numbers = [1, 2, 3, 4, 5];const doubled = numbers.map(n => n * 2);console.log(doubled); // => [2, 4, 6, 8, 10]console.log(numbers); // => [1, 2, 3, 4, 5] (original unchanged)
// Practical: extract property from array of objectsconst users = [ { name: "Alice", age: 30 }, { name: "Bob", age: 25 }, { name: "Charlie", age: 35 }];const names = users.map(user => user.name);console.log(names); // => ["Alice", "Bob", "Charlie"]filter — Select elements that pass a test
const numbers = [1, 2, 3, 4, 5, 6];const evens = numbers.filter(n => n % 2 === 0);console.log(evens); // => [2, 4, 6]
// Practical: filter active usersconst activeUsers = users.filter(user => user.age > 25);console.log(activeUsers); // => [{ name: "Alice", age: 30 }, { name: "Charlie", age: 35 }]reduce — Accumulate values
const numbers = [1, 2, 3, 4, 5];
// Sum all numbersconst sum = numbers.reduce((total, current) => total + current, 0);console.log(sum); // => 15
// Find maximumconst max = numbers.reduce((max, n) => n > max ? n : max, numbers[0]);console.log(max); // => 5
// Count occurrencesconst items = ["apple", "banana", "apple", "cherry", "banana", "apple"];const counts = items.reduce((acc, item) => { acc[item] = (acc[item] || 0) + 1; return acc;}, {});console.log(counts); // => { apple: 3, banana: 2, cherry: 1 }Spread Operator with Arrays
// Copyconst original = [1, 2, 3];const copy = [...original];console.log(copy); // => [1, 2, 3]
// Mergeconst arr1 = [1, 2];const arr2 = [3, 4];const merged = [...arr1, ...arr2];console.log(merged); // => [1, 2, 3, 4]
// Add elementsconst withInsert = [0, ...original, 4];console.log(withInsert); // => [0, 1, 2, 3, 4]Array Destructuring
const colors = ["red", "green", "blue", "yellow"];
const [first, second] = colors;console.log(first); // => "red"console.log(second); // => "green"
// Skip elementsconst [primary, , tertiary] = colors;console.log(primary); // => "red"console.log(tertiary); // => "blue"
// Rest patternconst [head, ...rest] = colors;console.log(head); // => "red"console.log(rest); // => ["green", "blue", "yellow"]
// Default valuesconst [a = 1, b = 2, c = 3] = [10];console.log(a, b, c); // => 10, 2, 3Joining and Splitting
// join — array to stringconst words = ["Hello", "World"];console.log(words.join(" ")); // => "Hello World"console.log(words.join("-")); // => "Hello-World"
// split — string to arrayconst csv = "apple,banana,cherry";console.log(csv.split(",")); // => ["apple", "banana", "cherry"]Sorting
const numbers = [3, 1, 10, 2, 20];numbers.sort(); // ❌ Sorts as strings: [1, 10, 2, 20, 3]console.log(numbers); // => [1, 10, 2, 20, 3]
// Correct: with comparatornumbers.sort((a, b) => a - b); // Ascendingconsole.log(numbers); // => [1, 2, 3, 10, 20]
numbers.sort((a, b) => b - a); // Descendingconsole.log(numbers); // => [20, 10, 3, 2, 1]
// Sorting objectsconst users = [ { name: "Bob", age: 25 }, { name: "Alice", age: 30 }, { name: "Charlie", age: 20 }];users.sort((a, b) => a.age - b.age); // Sort by age ascendingconsole.log(users.map(u => u.name)); // => ["Charlie", "Bob", "Alice"]Multidimensional Arrays
const matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]];
console.log(matrix[0][0]); // => 1console.log(matrix[1][2]); // => 6console.log(matrix[2][1]); // => 8
// Iteratefor (const row of matrix) { for (const cell of row) { console.log(cell); }}Try It Yourself
// 1. Create an array of numbers and use map to double each// 2. Use filter to get only positive numbers from [-3, 5, -1, 8, 0, 2]// 3. Use reduce to find the product of [1, 2, 3, 4, 5]// 4. Sort an array of objects by a string property// 5. Flatten [[1,2], [3,4], [5,6]] into [1,2,3,4,5,6] using reduce
const nested = [[1,2], [3,4], [5,6]];const flat = nested.reduce((acc, arr) => [...acc, ...arr], []);console.log(flat); // => [1, 2, 3, 4, 5, 6]Key Takeaways
- Use array methods (
map,filter,reduce) instead offorloops for data transformation maptransforms every element → returns new array (same length)filterselects matching elements → returns new array (same or shorter)reduceaccumulates values → returns any type (number, array, object)forEachis for side effects (logging, mutations)slicecreates a new array;splicemodifies the original- Always provide a comparator function to
sort()for numbers - Spread
...copies and merges arrays cleanly - Destructuring extracts elements:
const [first, second] = arr