LearnProgramming Course 1: Data Transformations

Continue on /course/functional.

The spreadsheet cases now become JavaScript data operations:

Column formula → map
Show matching rows → filter
SUM / COUNT / AVERAGE → reduce

ch07 — Map: Column Formulas

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.

Map: Price Transformation

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(...)

ch08 — Map: Text Transformations

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.

ch09 — Filter: Keep Matching Rows

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.

Filter: Menu Case

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.

ch10 — Reduce: Aggregate a Column

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.

Reduce = Spreadsheet Summary

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, Filter, Reduce Summary

map     transforms every item
filter  keeps matching items
reduce  combines all items

These three operations explain most spreadsheet data work and much everyday JavaScript.