Iterating arrays in JavaScript
The method decides what comes back: a value, a boolean, or a new array.
const runs = [
{ lang: "go", tpm: 104 },
{ lang: "rust", tpm: 98 },
{ lang: "sql", tpm: 79 },
];
console.log(runs.map((r) => r.lang));
console.log(runs.filter((r) => r.tpm > 90).length);
console.log(runs.reduce((total, r) => total + r.tpm, 0));
console.log(runs.some((r) => r.tpm > 100), runs.every((r) => r.tpm > 80));
console.log(runs.find((r) => r.lang === "rust")?.tpm);
console.log(runs.findLast((r) => r.tpm > 90)?.lang);
console.log(runs.flatMap((r) => [r.lang, r.tpm]).slice(0, 4));
console.log([...runs].sort((a, b) => a.tpm - b.tpm)[0].lang);
How it works
mapandfilterreturn arrays;reducereturns anything.someandeveryshort-circuit.find,findLastandfindIndexlocate one element.
Keywords and builtins used here
const
The run, in numbers
- Lines
- 14
- Characters to type
- 553
- Tokens
- 244
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 163 seconds.
Step 2 of 10 in Arrays, step 18 of 43 in Language basics.