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.

Build your intuition. 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

Try this exercise. 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

Build your intuition. 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

Try this exercise. 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

Try this exercise. 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

Let's test your knowledge. 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

Try this exercise. 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

Build your intuition. 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 facilitate transforming, searching, aggregating, and mutating lists of values with concise and readable code, essentially acting as small superpowers that simplify complex loops into one-liners.
  • The distinction between Mutating and Non-Mutating array methods is that the former alters the original array directly, while the latter creates a new array without changing the original, with many Non-Mutating methods supporting the principles of functional programming and pure functions.
  • In short, splice mutates the original array by removing and/or inserting elements in the same array object and returning an array of the removed elements.
  • Core Trio consists of map, filter, and reduce, where map is used to transform each element, filter keeps elements based on a predicate, and reduce combines all elements into a single value.
  • In JavaScript, the map method generates a new array of the same length as the original array, inserting undefined values for elements that are not explicitly returned in the callback function.
  • Reduce allows you to perform multiple operations in a single pass, such as calculating the sum of prices and grouping items by category using an accumulator that carries over the value returned each iteration.
  • For reduce to work, you must initialize the accumulator first, run the reducer on the current item and return the updated accumulator, and then move to the next item to repeat the process.
  • Key methods for searching in arrays include find, some, every, and includes, each serving different purposes such as retrieving the first matching element, checking for any matches, confirming all elements match, and directly checking for the presence of a value using strict equality.
  • The findIndex function in JavaScript returns the index of the first element that satisfies a predicate, as opposed to the find function which returns the element itself, with both methods stopping at the first match and findIndex returning -1 on no match, making it suitable for handling positions within arrays.
  • Slicing is a non-mutating operation that creates a copy of a subarray, while splicing is a mutating operation that allows for insertion and removal of elements within an array.
  • Immutable Newcomers in modern JS are non-mutating versions of classic mutators like sort, reverse, and splice, which return new arrays instead of altering the original.
  • Sorting by default sorts lexicographically as strings, so a compare function should be used for numeric sort.
  • flatMap applies a mapping function to each element and then flattens the result by one level, avoiding intermediate array creation and reducing iterations, ultimately replacing the two-step process of arr.map(fn).flat(1).
  • flat function flattens nested arrays up to a specified depth level, while flatMap function applies the map operation and then flattens one level.
  • The join(sep=',') function concatenates elements into a string, while the split(sep, limit?) function on strings breaks them into an array.
  • Aggregations that are commonly used on a daily basis, including examples for reference.
  • 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.