Skip to main content

Skillber v1.0 is here!

Learn more

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 slots

Accessing 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)
// Length
console.log(colors.length); // => 3
// Modify
colors[1] = "yellow";
console.log(colors); // => ["red", "yellow", "blue"]
// Last element
console.log(colors[colors.length - 1]); // => "blue"

Adding and Removing Elements

const items = ["a", "b", "c"];
// End
items.push("d"); // Add to end
console.log(items); // => ["a", "b", "c", "d"]
const last = items.pop(); // Remove from end
console.log(last); // => "d"
console.log(items); // => ["a", "b", "c"]
// Beginning
items.unshift("z"); // Add to beginning
console.log(items); // => ["z", "a", "b", "c"]
const first = items.shift(); // Remove from beginning
console.log(first); // => "z"
console.log(items); // => ["a", "b", "c"]

Finding Elements

const numbers = [10, 20, 30, 40, 50];
// indexOf — returns index or -1
console.log(numbers.indexOf(30)); // => 2
console.log(numbers.indexOf(99)); // => -1
// includes — boolean
console.log(numbers.includes(30)); // => true
console.log(numbers.includes(99)); // => false
// find — returns first matching element
const found = numbers.find(n => n > 25);
console.log(found); // => 30
// findIndex — returns index of first match
const index = numbers.findIndex(n => n > 25);
console.log(index); // => 2
// some/every — boolean checks
console.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 1
console.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: cherry

map — 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 objects
const 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 users
const 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 numbers
const sum = numbers.reduce((total, current) => total + current, 0);
console.log(sum); // => 15
// Find maximum
const max = numbers.reduce((max, n) => n > max ? n : max, numbers[0]);
console.log(max); // => 5
// Count occurrences
const 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

// Copy
const original = [1, 2, 3];
const copy = [...original];
console.log(copy); // => [1, 2, 3]
// Merge
const arr1 = [1, 2];
const arr2 = [3, 4];
const merged = [...arr1, ...arr2];
console.log(merged); // => [1, 2, 3, 4]
// Add elements
const 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 elements
const [primary, , tertiary] = colors;
console.log(primary); // => "red"
console.log(tertiary); // => "blue"
// Rest pattern
const [head, ...rest] = colors;
console.log(head); // => "red"
console.log(rest); // => ["green", "blue", "yellow"]
// Default values
const [a = 1, b = 2, c = 3] = [10];
console.log(a, b, c); // => 10, 2, 3

Joining and Splitting

// join — array to string
const words = ["Hello", "World"];
console.log(words.join(" ")); // => "Hello World"
console.log(words.join("-")); // => "Hello-World"
// split — string to array
const 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 comparator
numbers.sort((a, b) => a - b); // Ascending
console.log(numbers); // => [1, 2, 3, 10, 20]
numbers.sort((a, b) => b - a); // Descending
console.log(numbers); // => [20, 10, 3, 2, 1]
// Sorting objects
const users = [
{ name: "Bob", age: 25 },
{ name: "Alice", age: 30 },
{ name: "Charlie", age: 20 }
];
users.sort((a, b) => a.age - b.age); // Sort by age ascending
console.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]); // => 1
console.log(matrix[1][2]); // => 6
console.log(matrix[2][1]); // => 8
// Iterate
for (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 of for loops for data transformation
  • map transforms every element → returns new array (same length)
  • filter selects matching elements → returns new array (same or shorter)
  • reduce accumulates values → returns any type (number, array, object)
  • forEach is for side effects (logging, mutations)
  • slice creates a new array; splice modifies the original
  • Always provide a comparator function to sort() for numbers
  • Spread ... copies and merges arrays cleanly
  • Destructuring extracts elements: const [first, second] = arr