appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Array methods and destructuring

Lesson 1 of 411 minIntermediate

Transform data with map, filter and reduce, and unpack values cleanly.

Instead of loops that build results by hand, modern JavaScript transforms collections with methods that take a function. They return a new array and do not change the original (except sort, which does).

const products = [
  { name: "Pen", price: 2, stock: 10 },
  { name: "Book", price: 12, stock: 0 },
  { name: "Bag", price: 30, stock: 3 },
];

const names = products.map((p) => p.name);
const available = products.filter((p) => p.stock > 0);
const total = products.reduce((sum, p) => sum + p.price * p.stock, 0);
const book = products.find((p) => p.name === "Book");
const anyEmpty = products.some((p) => p.stock === 0);
const allCheap = products.every((p) => p.price < 50);
  • map transforms each item. filter keeps some. reduce combines all into one value.
  • find returns the first match (or undefined). some and every return booleans.
  • Chain them: products.filter(p => p.stock > 0).map(p => p.name).

Destructuring, spread and rest

const { name, price = 0 } = products[0];       // object destructuring with a default
const [first, ...others] = products;            // array destructuring and rest
const updated = { ...products[0], price: 3 };   // copy with a change (spread)
const more = [...products, { name: "Cap", price: 8, stock: 5 }];

CarefulSpread makes a shallow copy. Nested objects are still shared with the original. For a deep copy use structuredClone(value).

Notesort() changes the array in place and compares as strings by default. Use [...arr].sort((a, b) => a - b) for numbers without mutating the original.

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. Which method returns a new array with only some of the items?
2. What is [10, 9, 1].sort() without a compare function?
3. What does the spread copy { ...obj } not do?

Key terms