Skip to main content
Albero Academy

Array Methods in Depth

Beyond map/filter/reduce — find, some, every, sort, flat, and the difference between mutating and non-mutating methods.

Chapter 8JavaScript16 min readBeginner friendly
  • #JavaScript
  • #Arrays
  • #Methods

Chapter 3 introduced map, filter and reduce. Arrays have many more methods, and the single most important distinction to internalise is whether a method mutates the array in place or returns a new one — getting this wrong is a subtle, common source of bugs.

The big three, recap

map / filter / reduce
const nums = [1, 2, 3, 4];
nums.map(n => n * 2) // [2, 4, 6, 8] — transform
nums.filter(n => n % 2) // [1, 3] — keep
nums.reduce((a, n) => a + n, 0) // 10 — collapse
MethodReturns
findThe first matching element (or undefined)
findIndexThe index of the first match (or -1)
sometrue if any element passes
everytrue if all elements pass
includestrue if a value is present
finding things
const students = [
{ name: "Aanya", placed: true },
{ name: "Rohan", placed: false },
];
students.find(s => !s.placed) // { name: "Rohan", … }
students.some(s => s.placed) // true — at least one placed
students.every(s => s.placed) // false — not all placed
[1, 2, 3].includes(2) // true

Sorting

sort is the big trap: by default it sorts as strings, and it mutates the array. For numbers, pass a comparator:

sort correctly
[10, 2, 1].sort() // [1, 10, 2] ❌ string sort!
[10, 2, 1].sort((a, b) => a - b) // [1, 2, 10] ✓ ascending
[10, 2, 1].sort((a, b) => b - a) // [10, 2, 1] ✓ descending
// Sort objects by a field
students.sort((a, b) => a.name.localeCompare(b.name));
// Don't mutate the source — copy first:
const sorted = [...students].sort((a, b) => a.name.localeCompare(b.name));

Mutating vs non-mutating

immutable updates
const tools = ["Excel", "SQL"];
const added = [...tools, "Python"]; // add (new array)
const removed = tools.filter(t => t !== "SQL"); // remove (new array)
const updated = tools.map(t => t === "SQL" ? "PostgreSQL" : t);

flat & flatMap

nested arrays
[[1, 2], [3, 4]].flat() // [1, 2, 3, 4]
[[1, [2]], [3]].flat(2) // [1, 2, 3] (depth 2)
// flatMap = map then flatten one level
["a b", "c d"].flatMap(s => s.split(" ")) // ["a", "b", "c", "d"]

Practice

Given an array of student objects, use find to get one by name, some/every to check placement, and a non-mutating sort (on a copy) to order by package. Confirm the original array is unchanged.

Key takeaways

  1. 01find/findIndex return the first match; some/every test any/all; includes checks presence.
  2. 02sort defaults to string order and mutates — pass (a, b) => a - b and sort a copy for numbers.
  3. 03Mutating: sort, reverse, push, pop, splice. Non-mutating: map, filter, slice, concat, spread.
  4. 04Prefer non-mutating methods in state-driven code (React) to avoid subtle bugs.
  5. 05flat/flatMap flatten nested arrays.