TypeScript Tutorial
TypeScript Algorithms
sort, find, filter, and reduce work on arrays. Type the callback so the compiler checks the item.
Methods on the array, typed callbacks
C++ algorithms take two iterators: v.begin() and v.end(). TypeScript puts the same jobs on the array: sort, find, filter, reduce. You pass a function. Annotate that function’s parameter so tsc knows each item is a number (or astring, or your type).
The array-methods chapter introduced map, filter, and reduce. This page adds sort and find, and types every callback on purpose.
sort rearranges the array
sort changes the array in place. For numbers you must pass a comparator. The default sort converts values to strings, so 10 would come before 2. Return a negative number whena should come first.
Example
const temps: number[] = [18, 7, 21, 12, 9];
temps.sort((a: number, b: number) => a - b);
console.log(temps.join(" "));Output is 7 9 12 18 21. a - b is ascending. b - a would be descending. After the call, temps itself is sorted. There is no separate copy unless you slice first.
Open this at /typescript/try with Try it in TypeScript. Remove the comparator and run again: string order is not numeric order.
find locates one value
find walks the array until the callback returns true. It returns that element, orundefined if nothing matches. Check the result before you use it. Type the item so the predicate can compare numbers, not any.
Example
const lots: number[] = [11, 42, 8, 19, 5];
const found: number | undefined = lots.find((n: number) => n === 42);
if (found === undefined) {
console.log("missing");
} else {
console.log("found " + found);
}Output is found 42. Change 42 to 99 and the program printsmissing. find stops at the first match; it does not count the rest.
filter and reduce with typed items
The callback’s first parameter is one element. Write (n: number) (or your element type). Then a typo such as n.toUpperCase() is a compile error, not a crash later.
Example
const rolls: number[] = [3, 1, 3, 3, 6, 3];
const threes: number[] = rolls.filter((n: number) => n === 3);
const total: number = rolls.reduce((sum: number, n: number) => sum + n, 0);
console.log("threes: " + threes.length);
console.log("sum: " + total);Output is threes: 4 then sum: 19. filter returns a new array.reduce returns the seed plus every element. A missing value in filter yields an empty array, not an error.
Type the callback
| Call | Callback item | Returns |
|---|---|---|
sort | two elements to compare | void; rearranges in place |
find | one element | the item, or undefined |
filter | one element | a new array of matches |
reduce | accumulator and one element | the running total |
Inference often fills n: number in for you when the array is already number[]. Writing the annotation still documents the contract and catches a mismatched array type at the call.
Write a loop only when you must
A hand-written for that finds a max or a sum is fine while you learn. Once the work is “sort this” or “keep these,” prefer the named method. Next: arrow functions, the syntax those callbacks already used.