Docs
README
Module 12: Arrays
Overview
Arrays are ordered collections of values in JavaScript. They're one of the most commonly used data structures, providing powerful methods for storing, accessing, and manipulating lists of data.
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Array Structure β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β const fruits = ['apple', 'banana', 'cherry', 'date']; β
β β
β Index: 0 1 2 3 β
β βββββββ ββββββββ βββββββββ ββββββββ β
β βappleβ βbananaβ βcherry β β date β β
β βββββββ ββββββββ βββββββββ ββββββββ β
β β
β fruits[0] β 'apple' β
β fruits[3] β 'date' β
β fruits[-1] β undefined (use .at(-1) for last element) β
β fruits.length β 4 β
β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Topics Covered
12.1 Array Basics
- β’Creating arrays
- β’Accessing elements
- β’Array properties
- β’Array vs Object
12.2 Array Methods - Mutating
- β’push, pop, shift, unshift
- β’splice, sort, reverse
- β’fill, copyWithin
12.3 Array Methods - Non-Mutating
- β’slice, concat
- β’map, filter, reduce
- β’find, findIndex, includes
- β’every, some
12.4 Array Iteration
- β’forEach, for...of
- β’entries, keys, values
- β’Iteration patterns
12.5 Advanced Array Operations
- β’Flattening arrays
- β’Array destructuring
- β’Spread operator with arrays
- β’Array-like objects
12.1 Array Basics
Creating Arrays
// Array literal (most common)
const numbers = [1, 2, 3, 4, 5];
// Array constructor
const arr1 = new Array(3); // Creates array with 3 empty slots
const arr2 = new Array(1, 2, 3); // Creates [1, 2, 3]
// Array.of() - consistent behavior
const arr3 = Array.of(3); // Creates [3], not 3 empty slots
// Array.from() - from iterables
const arr4 = Array.from('hello'); // ['h', 'e', 'l', 'l', 'o']
const arr5 = Array.from({ length: 5 }, (_, i) => i * 2); // [0, 2, 4, 6, 8]
Accessing Elements
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Accessing Elements β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β const arr = ['a', 'b', 'c', 'd', 'e']; β
β β
β Bracket Notation: β
β arr[0] β 'a' (first) β
β arr[4] β 'e' (last by index) β
β arr[arr.length-1]β 'e' (last traditional) β
β β
β .at() Method (ES2022): β
β arr.at(0) β 'a' (first) β
β arr.at(-1) β 'e' (last) β
β arr.at(-2) β 'd' (second from end) β
β β
β Out of bounds: β
β arr[10] β undefined β
β arr.at(10) β undefined β
β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Array Properties
const arr = [1, 2, 3, 4, 5];
// Length
console.log(arr.length); // 5
// Modify length
arr.length = 3; // Truncates: [1, 2, 3]
arr.length = 5; // Extends: [1, 2, 3, empty Γ 2]
// Check if array
Array.isArray(arr); // true
Array.isArray('hello'); // false
12.2 Mutating Methods
These methods modify the original array.
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Mutating Methods β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β Adding/Removing: β
β ββββββββββββββββ β
β push(item) β Add to end β Returns new length β
β pop() β Remove from end β Returns removed item β
β unshift(item) β Add to start β Returns new length β
β shift() β Remove from startβ Returns removed item β
β β
β Modifying: β
β ββββββββββ β
β splice(i,n,...) β Remove/insert β Returns removed items β
β sort(fn) β Sort in place β Returns sorted array β
β reverse() β Reverse order β Returns reversed array β
β fill(value) β Fill with value β Returns filled array β
β β
β β οΈ These methods MODIFY the original array! β
β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
push / pop / unshift / shift
const stack = [];
// Add to end
stack.push('a'); // ['a'], returns 1
stack.push('b', 'c'); // ['a', 'b', 'c'], returns 3
// Remove from end
stack.pop(); // ['a', 'b'], returns 'c'
// Add to start
stack.unshift('x'); // ['x', 'a', 'b'], returns 3
// Remove from start
stack.shift(); // ['a', 'b'], returns 'x'
splice
const arr = ['a', 'b', 'c', 'd', 'e'];
// splice(startIndex, deleteCount, ...itemsToAdd)
// Remove elements
arr.splice(2, 1); // Removes 'c', arr = ['a', 'b', 'd', 'e']
// Insert elements
arr.splice(2, 0, 'x', 'y'); // arr = ['a', 'b', 'x', 'y', 'd', 'e']
// Replace elements
arr.splice(1, 2, 'z'); // arr = ['a', 'z', 'y', 'd', 'e']
// Negative index
arr.splice(-1, 1); // Removes last element
sort
// Default sort (converts to strings!)
[10, 2, 30, 1].sort(); // [1, 10, 2, 30] β οΈ Wrong!
// Numeric sort
[10, 2, 30, 1].sort((a, b) => a - b); // [1, 2, 10, 30] β
// Descending
[10, 2, 30, 1].sort((a, b) => b - a); // [30, 10, 2, 1]
// String sort (case-insensitive)
['Banana', 'apple', 'Cherry'].sort((a, b) =>
a.toLowerCase().localeCompare(b.toLowerCase())
);
// Object sort
const users = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 },
];
users.sort((a, b) => a.age - b.age);
12.3 Non-Mutating Methods
These methods return new arrays without modifying the original.
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Non-Mutating Methods β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β Creating new arrays: β
β ββββββββββββββββββββ β
β slice(start, end) β Extract portion β Returns new array β
β concat(...arrays) β Merge arrays β Returns new array β
β flat(depth) β Flatten nested β Returns new array β
β flatMap(fn) β Map then flatten β Returns new array β
β β
β Transformation: β
β βββββββββββββββ β
β map(fn) β Transform each β Returns new array β
β filter(fn) β Keep matching β Returns new array β
β reduce(fn, init) β Reduce to value β Returns accumulated β
β β
β Searching: β
β ββββββββββ β
β find(fn) β First match β Returns element β
β findIndex(fn) β First match indexβ Returns index β
β indexOf(item) β Index of item β Returns index β
β includes(item) β Contains item? β Returns boolean β
β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
slice
const arr = ['a', 'b', 'c', 'd', 'e'];
arr.slice(1, 3); // ['b', 'c'] (index 1 to 3, exclusive)
arr.slice(2); // ['c', 'd', 'e'] (from index 2 to end)
arr.slice(-2); // ['d', 'e'] (last 2 elements)
arr.slice(-3, -1); // ['c', 'd'] (negative indices)
arr.slice(); // ['a', 'b', 'c', 'd', 'e'] (shallow copy)
map
const numbers = [1, 2, 3, 4, 5];
// Transform each element
const doubled = numbers.map((n) => n * 2); // [2, 4, 6, 8, 10]
// Access index
const indexed = numbers.map((n, i) => `${i}: ${n}`);
// Extract property
const users = [{ name: 'John' }, { name: 'Jane' }];
const names = users.map((user) => user.name); // ['John', 'Jane']
filter
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evens = numbers.filter((n) => n % 2 === 0); // [2, 4, 6, 8, 10]
const big = numbers.filter((n) => n > 5); // [6, 7, 8, 9, 10]
// Filter objects
const users = [
{ name: 'John', active: true },
{ name: 'Jane', active: false },
];
const activeUsers = users.filter((user) => user.active);
reduce
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β reduce() Flow β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β [1, 2, 3, 4].reduce((acc, cur) => acc + cur, 0) β
β β
β Step 1: acc=0, cur=1 β 0 + 1 = 1 β
β Step 2: acc=1, cur=2 β 1 + 2 = 3 β
β Step 3: acc=3, cur=3 β 3 + 3 = 6 β
β Step 4: acc=6, cur=4 β 6 + 4 = 10 β
β β
β Result: 10 β
β β
β Syntax: array.reduce(callback, initialValue) β
β callback: (accumulator, currentValue, index, array) => ... β
β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const numbers = [1, 2, 3, 4, 5];
// Sum
const sum = numbers.reduce((acc, n) => acc + n, 0); // 15
// Max
const max = numbers.reduce((a, b) => Math.max(a, b)); // 5
// Count occurrences
const fruits = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple'];
const count = fruits.reduce((acc, fruit) => {
acc[fruit] = (acc[fruit] || 0) + 1;
return acc;
}, {});
// { apple: 3, banana: 2, cherry: 1 }
// Group by property
const people = [
{ name: 'John', age: 30 },
{ name: 'Jane', age: 25 },
{ name: 'Bob', age: 30 },
];
const byAge = people.reduce((acc, person) => {
const key = person.age;
(acc[key] = acc[key] || []).push(person);
return acc;
}, {});
find / findIndex
const users = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'Bob' },
];
const jane = users.find((user) => user.name === 'Jane');
// { id: 2, name: 'Jane' }
const janeIndex = users.findIndex((user) => user.name === 'Jane');
// 1
const unknown = users.find((user) => user.name === 'Unknown');
// undefined
const unknownIndex = users.findIndex((user) => user.name === 'Unknown');
// -1
every / some
const numbers = [2, 4, 6, 8, 10];
// every: ALL elements must pass
numbers.every((n) => n % 2 === 0); // true
numbers.every((n) => n > 5); // false
// some: AT LEAST ONE element must pass
numbers.some((n) => n > 5); // true
numbers.some((n) => n > 100); // false
12.4 Array Iteration
const arr = ['a', 'b', 'c'];
// forEach
arr.forEach((item, index) => {
console.log(`${index}: ${item}`);
});
// for...of (values only)
for (const item of arr) {
console.log(item);
}
// for...of with index using entries()
for (const [index, item] of arr.entries()) {
console.log(`${index}: ${item}`);
}
// Traditional for loop (when you need break/continue)
for (let i = 0; i < arr.length; i++) {
if (arr[i] === 'b') break;
console.log(arr[i]);
}
12.5 Advanced Operations
Flattening
const nested = [1, [2, 3], [4, [5, 6]]];
nested.flat(); // [1, 2, 3, 4, [5, 6]]
nested.flat(2); // [1, 2, 3, 4, 5, 6]
nested.flat(Infinity); // Flatten all levels
// flatMap (map + flat(1))
const sentences = ['Hello world', 'How are you'];
const words = sentences.flatMap((s) => s.split(' '));
// ['Hello', 'world', 'How', 'are', 'you']
Destructuring
const colors = ['red', 'green', 'blue', 'yellow'];
const [first, second] = colors; // first='red', second='green'
const [, , third] = colors; // third='blue'
const [head, ...rest] = colors; // head='red', rest=['green', 'blue', 'yellow']
// Default values
const [a = 'default', b] = []; // a='default', b=undefined
// Swap variables
let x = 1,
y = 2;
[x, y] = [y, x]; // x=2, y=1
Spread Operator
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
// Combine arrays
const combined = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]
// Copy array
const copy = [...arr1]; // [1, 2, 3]
// Insert in middle
const inserted = [...arr1.slice(0, 2), 'x', ...arr1.slice(2)];
// [1, 2, 'x', 3]
// Convert iterable to array
const chars = [...'hello']; // ['h', 'e', 'l', 'l', 'o']
Common Patterns
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Common Array Patterns β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β Remove duplicates: β
β [...new Set(array)] β
β β
β Filter + Map: β
β arr.filter(x => x > 0).map(x => x * 2) β
β β
β Find max/min: β
β Math.max(...numbers) β
β Math.min(...numbers) β
β β
β Check if empty: β
β arr.length === 0 β
β β
β Get random element: β
β arr[Math.floor(Math.random() * arr.length)] β
β β
β Shuffle array: β
β arr.sort(() => Math.random() - 0.5) // Simple but biased β
β β
β Create range: β
β Array.from({ length: 5 }, (_, i) => i) // [0,1,2,3,4] β
β β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Key Takeaways
- β’Arrays are zero-indexed ordered collections
- β’Mutating methods modify the original array
- β’Non-mutating methods return new arrays
- β’Use
map,filter,reducefor functional programming - β’Use
findfor first match,filterfor all matches - β’Use
everyto check all,someto check any - β’Spread operator
...for copying and combining - β’Destructuring for extracting values