Mark As Completed Discussion

Why Array Methods?

Array methods are built-in functions on JavaScript’s Array type that help you transform, search, aggregate, and mutate lists of values with clear, expressive code. Think of them as tiny superpowers that turn loops into readable one-liners.

Why Array Methods?

Two Families: Mutating vs Non-Mutating

  • Mutating methods: change the original array in place (push, pop, shift, unshift, splice, sort, reverse, fill, copyWithin).
  • Non-mutating methods: return a new array or value and leave the original unchanged (map, filter, slice, concat, flat, flatMap, toSorted, toReversed, toSpliced (new), reduce, some, every, find, findIndex, findLast, findLastIndex, includes, indexOf, lastIndexOf, join).

A pure function is one that has no side effects; many non-mutating methods help you write more functional code.

Let's test your knowledge. Click the correct answer from the options.

Which method mutates the original array?

Click the option that best answers the question.

  • `map`
  • `filter`
  • `slice`
  • `splice`

Core Trio: map, filter, reduce

  • map(fn): transform each element, returning a new array of equal length.
  • filter(fn): keep elements where the predicate is true.
  • reduce(fn, init): fold the array into a single value (sum, object, map).
JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Build your intuition. Is this statement true or false?

map can change the length of the resulting array.

Press true if you believe the statement is correct, or false otherwise.

reduce Deep Dive (with Comments)

Build two results with a single pass using reduce: 1) sum of prices, 2) group items by category.

Accumulator is the carry-over value you return each iteration; its shape is up to you.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Try this exercise. Could you figure out the right sequence for this list?

Put these steps of reduce in order:

Press the below buttons in the order in which they should occur. Click on them again to un-select.

Options:

  • Return the accumulator
  • Run reducer on current item
  • Initialize accumulator
  • Move to next item

Searching: find, some, every, includes

  • find(fn): first element that matches (or undefined).
  • some(fn): is there any match? returns boolean.
  • every(fn): do all match? returns boolean.
  • includes(value, fromIndex=0): direct value presence check (uses ===).
JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Let's test your knowledge. Fill in the missing part by typing it in.

__________ returns the index of the first matching element, while find returns the element itself.

Write the missing line below.

Slicing vs Splicing

  • slice(begin, end?): non-mutating copy of a subarray.
  • splice(start, deleteCount, ...items): mutating insertion/removal.
Slicing vs Splicing
JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Immutable Newcomers

Modern JS adds non-mutating versions of classic mutators:

  • toSorted(compareFn?) — like sort but returns a new array.
  • toReversed() — like reverse but non-mutating.
  • toSpliced(start, deleteCount, ...items) — like splice, but returns a new array.
JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Sorting Gotchas

sort by default sorts lexicographically (as strings). Use a compare function for numeric sort.

Sorting Gotchas
JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Are you sure you're getting this? Click the correct answer from the options.

Which method both flattens and maps in one pass?

Click the option that best answers the question.

  • `flat`
  • `flatMap`
  • `map`
  • `concat`

flat and flatMap

  • flat(depth=1): flattens nested arrays up to depth.
  • flatMap(fn): applies map, then flattens one level.
JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Joining and Splitting

  • join(sep=','): concatenate elements into a string.
  • split(sep, limit?): (on strings) break into an array.
JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Aggregations You’ll Use Daily

These are every day aggregations you'll encounter daily, with examples.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Build your intuition. Is this statement true or false?

indexOf works for objects by structural equality.

Press true if you believe the statement is correct, or false otherwise.

Insertion & Removal Patterns (Immutable)

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Performance & Pitfalls

  • O(n) nature: many array ops traverse the entire list; avoid repeated concat in loops—prefer one push per item or build then join.
  • Copy vs reference: methods like slice copy references for objects; nested structures still share inner objects.
  • sort is in-place; prefer toSorted if immutability matters.

Project: CSV to Summary with Array Methods

Here, we parse a tiny CSV (no quotes/escapes) and summarize sales by product.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Build your intuition. Click the correct answer from the options.

Which sequence keeps the original array unchanged while returning a sorted copy?

Click the option that best answers the question.

  • `arr.sort()`
  • `[...arr].sort()`
  • `arr.toSorted()`
  • Both B and C

Defensive Patterns

  • Use Array.isArray(x) to check arrayness; typeof [] === 'object'.
  • Destructure with defaults to avoid undefined issues in callbacks.
  • Prefer Number.isFinite when parsing numeric arrays.
JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Try this exercise. Fill in the missing part by typing it in.

The map callback receives three parameters: currentValue, index, and __________.

Write the missing line below.

Practice: Implement map & filter from Scratch

DO NOT use built-ins inside implementations; use simple loops.

Sparse array has “holes” (missing indices). Native methods skip them; we mirrored that.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

One Pager Cheat Sheet

  • Array methods are built-in functions on JavaScript’s Array type that let you transform, search, aggregate, and mutate lists of values using clear, expressive code, effectively turning loops into readable one-liners.
  • JavaScript arrays fall into two families—mutating methods like push, pop, splice, sort, reverse that change the original array in place, and non-mutating methods like map, filter, slice, concat, reduce that return new values and leave the original unchanged, which helps you write pure functions and more functional code.
  • The splice method mutates the original array by removing and/or inserting elements (and updating indices/length) and returns the removed elements, so it produces a side effect and is not a pure function, unlike non-mutating alternatives such as slice, map, concat, or the newer toSpliced (or you can build a new array with let b = [...a.slice(0,i), ...newItems, ...a.slice(i+deleteCount)]).
  • map transforms each element producing a new array of the same length, filter keeps elements that satisfy a predicate, and reduce folds the array into a single value (e.g., sum, object, map).
  • map always preserves the original array length and index positions: it transforms each element by calling the callback (returning undefined still yields an element) and — for sparse arrays — it does not call the callback for holes so they remain, so to change the number of elements use filter or flatMap.
  • Use reduce to build two results in a single pass — a sum of prices and group items by category — by returning an Accumulator (the carry-over value) whose shape is up to you each iteration.
    1. Initialize accumulator
  1. Run reducer on current item
  2. Return the accumulator
  3. Move to next item

You must first initialize the accumulator (via an explicit initialValue or the first element) so the reducer can process each currentValue, return the updated accumulator to serve as the carry-over, and only then move to the next item, allowing reduce to perform single-pass computations by carrying a combined state.

  • Use find(fn) to return the first matching element (or undefined), some(fn) to test if any element matches (boolean), every(fn) to check if all elements match (boolean), and includes(value, fromIndex=0) to check for direct value presence using strict equality (===).
  • find returns the element (or undefined) while findIndex returns the index (or -1); both take a predicate callback and short-circuit, so use find for the element value and findIndex for the position (e.g., to splice/update), and note that includes differs by checking a value with === and returning a boolean—both find and findIndex run in O(n).
  • slice(begin, end?) creates a non-mutating copy of a subarray, whereas splice(start, deleteCount, ...items) performs mutating insertion and/or removal of elements.
  • Modern JavaScript introduces non-mutating versions of classic mutatorstoSorted(compareFn?), toReversed(), and toSpliced(start, deleteCount, ...items) — which return new arrays instead of modifying the original.
  • By default, sort sorts lexicographically (as strings), so use a compare function for numeric sort.
  • flatMap combines mapping and one-level flattening in a single pass by calling a callback for each element and immediately concatenating its (possibly array) result, which avoids creating an intermediate array that map(...).flat(1) would produce.
  • flat(depth=1) flattens nested arrays up to the given depth, whereas flatMap(fn) applies map then flattens the result by one level.
  • Use join(sep=',') to concatenate elements into a string and split(sep, limit?) (on strings) to break a string into an array.
  • A concise guide to aggregations you'll use daily, presenting common aggregations with practical examples.
  • indexOf in JavaScript does not perform structural (deep) equality for objects; it relies on reference (identity) equality.
  • This section addresses insertion and removal patterns for immutable data structures.
  • Performance & Pitfalls include the O(n) nature of many array operations, the distinction between copying vs referencing objects, and the importance of considering immutability when using the sort method.
  • Project is focused on converting a small CSV file with no quotes or escapes into a summary of sales by product using Array Methods.
  • Both B and C create a new (shallow) array copy of the original array using slice() and the spread syntax, then use sort to return the sorted copy while leaving the original array unchanged.
  • When working with arrays, use Array.isArray(x) for array checking, use destructuring with defaults to avoid undefined issues, and prefer Number.isFinite when working with numeric arrays.
  • The array parameter in a map callback provides access to the original array being iterated over, allowing for contextual operations within the callback function.
  • map and filter functions were implemented from scratch without using built-in methods, with the consideration of handling sparse arrays by skipping "holes" in the indices, similar to the behavior of native methods.