JavaScript Tutorial
Module 5: Arrays, Objects, and Collections
Array Methods: map, filter, find, reduce
Transform, select, search, and aggregate arrays using readable methods.
10 minute lessonBeginner to intermediate
Array methods communicate common collection operations without manual index management.
maptransforms each item and returns an array of the same length.filterreturns items that pass a condition.findreturns the first matching item orundefined.somechecks whether at least one item matches;everychecks whether all do.reducecombines items into one accumulated result.
const lessons = [
{ title: "Variables", minutes: 8, complete: true },
{ title: "Functions", minutes: 12, complete: false },
{ title: "Objects", minutes: 10, complete: true },
];
const titles = lessons.map(lesson => lesson.title);
const incomplete = lessons.filter(lesson => !lesson.complete);
const firstLongLesson = lessons.find(lesson => lesson.minutes > 10);
const totalMinutes = lessons.reduce((sum, lesson) => sum + lesson.minutes, 0);
Avoid side effects in transformations#
Keep map and filter callbacks focused on returning values. Mutating external state from inside a transformation can make behaviour harder to follow. If a regular loop better communicates your intent, use it.
Sorting#
sort mutates the original array. Use toSorted in modern environments when you want a sorted copy, or spread/slice before sorting for broader compatibility.
const scores = [10, 3, 21];
const ascending = [...scores].sort((a, b) => a - b);
Practice#
Given an array of products, return only products in stock, map them to names, and calculate the sum of their prices.