CodeOath
← All posts
JavaScript65 min total · 16 parts

JavaScript Array and Object Methods Cheat Sheet

Contents — Part 15 of 16: A Worked Example Combining Several of These
Part 15 of 16 · ~1 min

A Worked Example Combining Several of These

Diagram of a filter then map pipeline turning a users array into a list of active adults' names

const users = [
  { name: "Alice", age: 30, active: true },
  { name: "Bob", age: 17, active: false },
  { name: "Carol", age: 25, active: true },
];

const activeAdultNames = users
  .filter(u => u.active && u.age >= 18)
  .map(u => u.name);
// ["Alice", "Carol"]

const byName = Object.fromEntries(users.map(u => [u.name, u]));
// { Alice: {...}, Bob: {...}, Carol: {...} } — quick lookup table by name

const averageAge = users.reduce((sum, u) => sum + u.age, 0) / users.length;
// 24 — reduce for a running total, then a plain division

This chain — filter, then map — is one of the most common patterns in real JavaScript code, and it reads almost exactly like the English description of what it does. Combining .reduce() with Object.fromEntries() for lookup tables, and chaining .filter().map() for transforming lists of records, covers a large share of the data-shaping code in a typical frontend or Node.js codebase.