📦beginner
Arrays & Methods
Arrays store ordered lists of values. Master the essential array methods — map, filter, reduce, and more — to write expressive, functional-style code.
Creating Arrays
hljs javascript
// Literal (preferred)
const nums = [1, 2, 3, 4, 5];
const mixed = [1, "two", true, null, { x: 1 }];
const empty = [];
// Array constructor
const zeros = new Array(5).fill(0); // [0, 0, 0, 0, 0]
const range = Array.from({ length: 5 }, (_, i) => i); // [0, 1, 2, 3, 4]
// From iterables
const chars = Array.from("hello"); // ["h","e","l","l","o"]
const fromSet = Array.from(new Set([1, 2, 2, 3])); // [1, 2, 3]
Accessing and Modifying
hljs javascript
const fruits = ["apple", "banana", "cherry"];
// Access
console.log(fruits[0]); // "apple"
console.log(fruits.at(-1)); // "cherry" (negative index, ES2022)
// Modify
fruits[1] = "blueberry";
// Length
console.log(fruits.length); // 3
Adding and Removing Elements
hljs javascript
const arr = [1, 2, 3];
// End
arr.push(4, 5); // add to end → [1, 2, 3, 4, 5]
arr.pop(); // remove from end → returns 5, arr is [1, 2, 3, 4]
// Start
arr.unshift(0); // add to start → [0, 1, 2, 3, 4]
arr.shift(); // remove from start → returns 0, arr is [1, 2, 3, 4]
// Arbitrary position (splice)
arr.splice(1, 2); // remove 2 elements at index 1 → [1, 4]
arr.splice(1, 0, 2, 3); // insert at index 1 → [1, 2, 3, 4]
arr.splice(1, 1, 99); // replace → [1, 99, 3, 4]
Searching
hljs javascript
const arr = [10, 20, 30, 20, 40];
arr.indexOf(20); // 1 (first occurrence)
arr.lastIndexOf(20); // 3 (last occurrence)
arr.includes(30); // true
arr.find(x => x > 25); // 30 (first match)
arr.findIndex(x => x > 25); // 2 (index of first match)
arr.findLast(x => x < 35); // 30 (ES2023, last match)
The Essential Array Methods
These are the workhorses of modern JavaScript:
map — Transform Each Element
hljs javascript
const prices = [10, 20, 30, 40];
const withTax = prices.map(p => p * 1.1);
console.log(withTax); // [11, 22, 33, 44]
const users = [
{ name: "Alice", age: 30 },
{ name: "Bob", age: 25 },
];
const names = users.map(u => u.name);
console.log(names); // ["Alice", "Bob"]
filter — Keep Matching Elements
hljs javascript
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4, 6, 8, 10]
const adults = users.filter(u => u.age >= 18);
reduce — Accumulate to a Single Value
hljs javascript
const nums = [1, 2, 3, 4, 5];
// Sum
const sum = nums.reduce((acc, n) => acc + n, 0);
console.log(sum); // 15
// Product
const product = nums.reduce((acc, n) => acc * n, 1);
console.log(product); // 120
// Max
const max = nums.reduce((max, n) => n > max ? n : max, -Infinity);
console.log(max); // 5
// Count occurrences
const words = ["the", "cat", "sat", "on", "the", "mat"];
const freq = words.reduce((acc, word) => {
acc[word] = (acc[word] || 0) + 1;
return acc;
}, {});
console.log(freq); // { the: 2, cat: 1, sat: 1, on: 1, mat: 1 }
// Flatten
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]
💡reduce signature
array.reduce(callback, initialValue) where callback receives (accumulator, currentValue, currentIndex, array). Always provide an initialValue — omitting it uses the first element as the initial accumulator and can cause bugs on empty arrays.
forEach — Side Effects
hljs javascript
const items = ["a", "b", "c"];
items.forEach((item, index) => {
console.log(`${index}: ${item}`);
});
// Use for side effects (logging, DOM updates)
// forEach returns undefined — don't use for transformation
some and every
hljs javascript
const ages = [16, 22, 18, 25, 14];
const hasAdult = ages.some(age => age >= 18); // true
const allAdults = ages.every(age => age >= 18); // false
flat and flatMap
hljs javascript
const nested = [1, [2, 3], [4, [5, 6]]];
nested.flat(); // [1, 2, 3, 4, [5, 6]] — one level
nested.flat(2); // [1, 2, 3, 4, 5, 6] — two levels
nested.flat(Infinity); // fully flatten
// flatMap = map + one level of flat
const sentences = ["Hello World", "Foo Bar"];
const words = sentences.flatMap(s => s.split(" "));
console.log(words); // ["Hello", "World", "Foo", "Bar"]
Sorting
hljs javascript
const letters = ["banana", "apple", "cherry"];
letters.sort(); // ["apple", "banana", "cherry"] (alphabetical)
// ⚠️ Numbers sort as strings by default!
[10, 9, 2, 100].sort(); // [10, 100, 2, 9] — wrong!
// Correct numeric sort:
[10, 9, 2, 100].sort((a, b) => a - b); // [2, 9, 10, 100] ✓
// Descending
[10, 9, 2, 100].sort((a, b) => b - a); // [100, 10, 9, 2]
// Sort objects
const people = [
{ name: "Charlie", age: 25 },
{ name: "Alice", age: 30 },
{ name: "Bob", age: 20 },
];
people.sort((a, b) => a.name.localeCompare(b.name));
// sorted by name alphabetically
Copying Arrays
hljs javascript
const original = [1, 2, 3];
const copy1 = [...original]; // spread (shallow)
const copy2 = original.slice(); // slice (shallow)
const copy3 = Array.from(original); // Array.from (shallow)
// Deep copy (for nested arrays/objects):
const deepCopy = JSON.parse(JSON.stringify(original));
// Or use structuredClone() (modern browsers):
const deepCopy2 = structuredClone(original);
Chaining Methods
Methods can be chained because each returns a new array:
hljs javascript
const data = [
{ name: "Alice", score: 88, active: true },
{ name: "Bob", score: 72, active: false },
{ name: "Charlie", score: 95, active: true },
{ name: "Dave", score: 61, active: true },
];
const result = data
.filter(d => d.active) // keep active
.sort((a, b) => b.score - a.score) // sort by score descending
.map(d => `${d.name}: ${d.score}`) // format
.slice(0, 2); // top 2
console.log(result); // ["Charlie: 95", "Alice: 88"]
▶Try it yourself
Key Takeaways
push/popfor the end;unshift/shiftfor the start;splicefor anywheremap— transform (returns new array);filter— select;reduce— accumulatesome/every— boolean checks;find/findIndex— searching- Avoid
sort()on numbers — always provide a comparator:(a, b) => a - b - Array methods are chainable — build pipelines for clean data transformations
Ready to test your knowledge?
Take a quiz on what you just learned.