JavaScript Intermediate Language Basics · 8 min read

JavaScript Array Methods: map, filter, reduce, find, some, every

Lesson 3 of 38 in the JavaScript learning path.

How do I transform and test arrays without a manual loop?

map, filter, reduce, find, some, and every walk an array without a hand-written index loop. map builds a new array of transformed values, such as student names. filter builds a new array of the items that pass a test, such as active students at a passing score. reduce folds the array into one result, such as an average. find returns the first match or undefined, while some and every return booleans.

None of these six methods replace items in the original roster when the callback only reads fields and returns a new value. That matters on a grade dashboard: the source list stays available for a second widget after the passing list has been drawn. The average of this sample roster is exact, and a second read of the scores matches the first. Keep callbacks pure so a later sort or export still sees the scores that were loaded.

Syntax & Parameters

Syntax
array.map(fn)
array.filter(fn)
array.reduce(fn, initial)
array.find(fn)
array.some(fn)
array.every(fn)

Example

Interactive preview available
app.js
'use strict';

const roster = [
  { name: 'Amina', track: 'web', score: 92, active: true },
  { name: 'Luis', track: 'web', score: 74, active: true },
  { name: 'Priya', track: 'data', score: 88, active: false },
  { name: 'Jonah', track: 'web', score: 81, active: true },
  { name: 'Mei', track: 'data', score: 95, active: true },
];

const originalScores = roster.map((student) => student.score);
const names = roster.map((student) => student.name);
const passing = roster.filter((student) => student.active && student.score >= 80);
const average = roster.reduce((total, student) => total + student.score, 0) / roster.length;
const firstData = roster.find((student) => student.track === 'data');
const anyInactive = roster.some((student) => student.active === false);
const everyNamed = roster.every((student) => student.name.trim() !== '');
const scoresAfter = roster.map((student) => student.score);

const report = {
  names,
  passing: passing.map((student) => `${student.name} (${student.score})`),
  average,
  firstData: firstData ? firstData.name : null,
  anyInactive,
  everyNamed,
  originalScores,
  scoresAfter,
  sameScores: originalScores.every((score, index) => score === scoresAfter[index]),
};

const summary = document.getElementById('roster-summary');
if (summary !== null) {
  summary.textContent = JSON.stringify(report, null, 2);
}

const list = document.getElementById('passing-list');
if (list !== null) {
  list.replaceChildren();
  for (const student of passing) {
    const item = document.createElement('li');
    item.textContent = `${student.name} (${student.score})`;
    list.append(item);
  }
}

console.log(JSON.stringify(report, null, 2));

Expected Output

Console and #roster-summary:

{
  "names": ["Amina", "Luis", "Priya", "Jonah", "Mei"],
  "passing": ["Amina (92)", "Jonah (81)", "Mei (95)"],
  "average": 86,
  "firstData": "Priya",
  "anyInactive": true,
  "everyNamed": true,
  "originalScores": [92, 74, 88, 81, 95],
  "scoresAfter": [92, 74, 88, 81, 95],
  "sameScores": true
}

#passing-list:
- Amina (92)
- Jonah (81)
- Mei (95)

Line-by-Line Walkthrough

  1. roster is a const array of five student objects with a name, track, score, and active flag, and the callbacks never assign back into it.
  2. The first map stores the five scores so a later map can prove the source numbers did not change.
  3. The second map returns only the names, in the original order, as a new array.
  4. filter keeps students who are active and scored at least 80, so Priya and Luis drop out and Amina, Jonah, and Mei remain.
  5. reduce starts at 0, adds every score, and divides by the roster length to get the average 86.
  6. find returns the first data-track student, Priya, even though that student is inactive. some reports that at least one student is inactive.
  7. every checks that each name has non-empty text after trim, which is true for this roster.
  8. scoresAfter maps the scores again, and sameScores compares them with the first snapshot index by index.
  9. The summary element receives the JSON through textContent, so the report is shown as text.
  10. The passing students are added to the list with createElement and textContent, one li at a time, without writing an HTML string.

Common Pitfalls & Security

These methods return new arrays or a folded value, but the callback can still mutate each student object if it assigns to a field. A map that sets student.passed = true changes the objects inside the original roster. reduce without an initial value uses the first item as the accumulator and skips that item as a source, which is a bad fit for a numeric average. find returns the object itself, not a copy, so editing that result edits the roster.

  • Assigning list.innerHTML to a joined name string parses markup. A name equal to the untrusted string <img src="x" alt="untrusted"> becomes a real element and is an XSS hole. Use textContent on each item instead.
  • filter and map do not update the array you called them on. Reassign the result, or you will think the roster changed when it did not.
  • some stops at the first success and every stops at the first failure. Do not rely on them to visit every student for a side effect.
  • An empty roster makes reduce with an initial value return that initial value. Without an initial value it throws.
  • Sorting the roster with sort mutates it. Use toSorted when the grade table must keep the loaded order.

Best Practices & Modern Standards

Choose the method that matches the result you need: map for a same-length transform, filter for a subset, reduce for one accumulated value, find for the first match, and some or every for a yes-or-no test. Pass an initial value to reduce whenever the accumulator is a number or a fresh object. In ES2024 code, Object.groupBy can split a roster by track without a manual reduce, and toSorted can order a copy after filter.

Keep the callback pure. Read fields, return a new value, and build DOM nodes from the resulting array in a separate step. That split lets a dashboard recompute the passing list when a score changes without surprising the export button that still needs the original objects. Guard find with a check before you read a property, because a missing match is undefined.

Real-World Use

A grade dashboard loads one roster and shows three views from it. map feeds the name column, filter feeds the passing list, and reduce feeds the average in the header. find jumps to the first data-track student when a teacher clicks that track, and some lights a warning when any enrollment is inactive. every can disable the export button until every row has a name.

Because the callbacks do not edit the loaded objects, a second widget can still show the original scores after the passing list is on screen. The list itself is built with elements and text, so a student name that contains markup stays visible as text in the table.

Frequently Asked Questions

Do map and filter change the original array?

They return new arrays and leave the source array length and order alone. They do not freeze the objects inside the array. If the callback assigns to a property, that object changes everywhere it is shared.

Why pass an initial value to reduce?

The initial value is the starting accumulator, so the first student is included in the calculation. Without it, reduce uses the first array item and throws on an empty array. A numeric total should start at 0.

How is find different from filter?

find returns the first matching item, or undefined when nothing matches. filter returns every match in a new array, which is empty when nothing matches. Use find for a jump-to-student action and filter for a list.

When should I use some instead of every?

some returns true as soon as one item passes the test, which fits a warning that any student is inactive. every returns true only when all items pass, which fits a check that every name is present. Neither one builds a new array.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…