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…MethodReturnsExample
to turn every item into something elsemapa new array of the same lengthnums.map((n) => n * 2)
only some of the itemsfiltera new, shorter arrayusers.filter((u) => u.active)
the first item matching a conditionfindthe item, or undefinedusers.find((u) => u.id === id)
does it contain a value?includestrue / falsetags.includes('react')
does at least one match?sometrue / falsecart.some((i) => !i.inStock)
one value from the whole arrayreduceanythingitems.reduce((sum, i) => sum + i.price, 0)
a sorted copytoSorteda new arraynums.toSorted((a, b) => a - b)
a sliceslicea new arraylist.slice(0, 3)
do all of them match?everytrue / falsefields.every((f) => f.valid)
the position of the first such itemfindIndexan index, or -1list.findIndex((x) => x.done)
without duplicatesnew Setan array via spread[...new Set(tags)]
groups by a propertyObject.groupByan object of arraysObject.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 endarr.push(x)[...arr, x]
change one itemarr[i].done = truearr.map((x) => (x.id === id ? { ...x, done: true } : x))
remove by idarr.splice(i, 1)arr.filter((x) => x.id !== id)
change an object propertyobj.name = 'x'{ ...obj, name: 'x' }
add to the startarr.unshift(x)[x, ...arr]
a nested propertyobj.address.city = 'x'{ ...obj, address: { ...obj.address, city: 'x' } }
sortarr.sort(fn)arr.toSorted(fn)
reversearr.reverse()arr.toReversed()

In detail: lesson 0.9.