Lesson 8
reduce, sort & analysis
Build a practical mental model for reduce, sort & analysis and use it in working JavaScript.
By the end, you will be able to…
- Explain reduce, sort & analysis in your own words
- Use reduce, sort & analysis in a small program
- Recognize and debug a common failure mode
Build the mental model
reduce folds an entire array down to a single value (a total, a grouped object, a maximum) using an accumulator. sort compares elements pairwise using a comparator you supply — without one, it sorts lexicographically, surprising anyone sorting numbers.
Syntax and working example
Read the code from inputs to output. Predict what it prints, then run it and change one value.
Why this matters
reduce is the most general array method — map and filter can both be written in terms of it — so understanding it well unlocks custom aggregations.
Real-world example
A dashboard computing 'total revenue this month' from a list of orders is a single reduce call over real transaction data.
Common mistakes
- Forgetting the initial value in reduce, causing the first element to be used unexpectedly as the accumulator
- Sorting numbers without a comparator and getting lexicographic order (e.g. [10, 2, 1])
- Mutating the original array with sort instead of copying first
Try it yourself
Challenge
Fix the numeric sort so [10, 2, 1] sorts correctly using a comparator.
Knowledge check
What happens if you call array.sort() on numbers with no comparator?
Summary
Use reduce to fold an array to one value, and always pass a comparator when sorting numbers.