Continue on /course/functional.
The spreadsheet cases now become JavaScript data operations:
Column formula → map
Show matching rows → filter
SUM / COUNT / AVERAGE → reduce
Dragging =A1+3 down a spreadsheet column applies one rule to every row.
const A = [1, 2, 3, 4]
const B = A.map(x => x + 3)
// B is [4, 5, 6, 7]
.map() creates a new array. It does not change A.
const prices = [50, 40, 120, 60]
const pricesWithTax = prices.map(price => price * 1.1)
// [55, 44, 132, 66]
| Excel | JavaScript |
|---|---|
| Write a formula in B1 | Write price => price * 1.1
|
| Drag down the column | Call .map(...)
|
Map works on text as well as numbers.
const names = ["ada", "grace", "linus"]
const upperNames = names.map(name => name.toUpperCase())
const lengths = names.map(name => name.length)
// ["ADA", "GRACE", "LINUS"]
// [3, 5, 5]
One input item produces one output item.
Filtering is a question that returns true or false.
const scores = [85, 92, 78, 95, 88]
const passing = scores.filter(score => score >= 80)
// [85, 92, 95, 88]
If the test is true, keep the item. If false, remove it.
const menu = [
{ name: "Coffee", price: 50 },
{ name: "Tea", price: 40 },
{ name: "Cake", price: 120 },
{ name: "Steak", price: 350 }
]
const under100 = menu.filter(item => item.price <= 100)
// Coffee and Tea
This is the same as showing only spreadsheet rows whose Price column is at most 100.
reduce combines many values into one value.
const scores = [85, 92, 78, 95, 88]
const total = scores.reduce((sum, score) => sum + score, 0)
// 438
The 0 is the starting value. sum carries the running total.
const prices = [50, 40, 120, 60]
const total = prices.reduce((sum, price) => sum + price, 0)
const count = prices.length
const average = total / count
| Spreadsheet | JavaScript |
|---|---|
=SUM(A:A) |
.reduce((sum, x) => sum + x, 0) |
=COUNT(A:A) |
.length |
=AVERAGE(A:A) |
total / count |
map transforms every item
filter keeps matching items
reduce combines all items
These three operations explain most spreadsheet data work and much everyday JavaScript.