typestar

Array methods in JavaScript

The iteration methods that replace most for loops.

const nums = [5, 12, 8, 130, 44];

const doubled = nums.map((n) => n * 2);
const large = nums.filter((n) => n > 10);
const total = nums.reduce((sum, n) => sum + n, 0);

const found = nums.find((n) => n > 100);
const index = nums.findIndex((n) => n > 100);
const anyBig = nums.some((n) => n > 100);
const allPositive = nums.every((n) => n > 0);

const sorted = [...nums].sort((a, b) => a - b);

How it works

  1. map, filter, and reduce transform and fold.
  2. find, some, and every answer questions.
  3. sort mutates, so spread into a copy first.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
392
Tokens
152
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 101 seconds.

Type this snippet

Step 1 of 10 in Arrays, step 17 of 43 in Language basics.

← Previous Next →