Cheat sheets
Cheat sheets
The most important things on one page – array methods, React hooks and TypeScript in React, the most used first. Print them or keep them open next to your code.
Array methods: I want… → use
| I want… | Method | Returns | Example |
|---|---|---|---|
| to turn every item into something else | map | a new array of the same length | nums.map((n) => n * 2) |
| only some of the items | filter | a new, shorter array | users.filter((u) => u.active) |
| the first item matching a condition | find | the item, or undefined | users.find((u) => u.id === id) |
| does it contain a value? | includes | true / false | tags.includes('react') |
| does at least one match? | some | true / false | cart.some((i) => !i.inStock) |
| one value from the whole array | reduce | anything | items.reduce((sum, i) => sum + i.price, 0) |
| a sorted copy | toSorted | a new array | nums.toSorted((a, b) => a - b) |
| a slice | slice | a new array | list.slice(0, 3) |
| do all of them match? | every | true / false | fields.every((f) => f.valid) |
| the position of the first such item | findIndex | an index, or -1 | list.findIndex((x) => x.done) |
| without duplicates | new Set | an array via spread | [...new Set(tags)] |
| groups by a property | Object.groupBy | an object of arrays | Object.groupBy(items, (i) => i.category) |
In detail: lesson 0.4 and lesson 0.5.
Immutable updates (state in React)
| Change | ❌ Mutates the original | ✅ Returns a new one |
|---|---|---|
| add to the end | arr.push(x) | [...arr, x] |
| change one item | arr[i].done = true | arr.map((x) => (x.id === id ? { ...x, done: true } : x)) |
| remove by id | arr.splice(i, 1) | arr.filter((x) => x.id !== id) |
| change an object property | obj.name = 'x' | { ...obj, name: 'x' } |
| add to the start | arr.unshift(x) | [x, ...arr] |
| a nested property | obj.address.city = 'x' | { ...obj, address: { ...obj.address, city: 'x' } } |
| sort | arr.sort(fn) | arr.toSorted(fn) |
| reverse | arr.reverse() | arr.toReversed() |
In detail: lesson 0.9.