typestar

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

  1. map and filter return arrays; reduce returns anything.
  2. some and every short-circuit.
  3. find, findLast and findIndex locate one element.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 10 in Arrays, step 18 of 43 in Language basics.

← Previous Next →