October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

JavaScript Array Methods: Choose by the Result You Need

Choose JavaScript array methods by the result you need: transform, select, find, test, combine, or flatten data.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose a JavaScript array method by the shape of the result you need: use map() to transform every item, filter() to keep some items, find() to get the first match, some() or every() for a yes-or-no test, reduce() to combine values, and flatMap() to map items to zero or more results. The callback’s return value is what determines what these methods produce.

Start with the result you want

Imagine a task list in a course app. Each task has a title, completion status, estimated time, and tags:

As an Amazon Associate I earn from qualifying purchases.

const tasks = [
  { id: 1, title: "Read the lesson", complete: true, minutes: 15, tags: ["reading", "basics"] },
  { id: 2, title: "Build a counter", complete: false, minutes: 30, tags: ["project", "basics"] },
  { id: 3, title: "Review examples", complete: false, minutes: 10, tags: [] }
];

Each method below answers a different question about that same data. A useful first decision is whether your result should be an array, one item, a boolean, or a single accumulated value.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Need Method Typical result
Convert each item map() A new array of callback results
Keep matching items filter() A new array of passing items
Get the first matching item find() An item or undefined
Check whether at least one item matches some() A boolean
Check whether all visited items pass every() A boolean
Combine items into one result reduce() The final accumulator value
Map each item to zero or more results and flatten one level flatMap() A new array

These are the everyday mental models; details such as sparse arrays and array-like objects have additional rules in MDN’s Array reference.

Transform every item with map()

Use map() when each input item should produce a corresponding output value. The callback’s returned value becomes an element in the new array:

const taskTitles = tasks.map(task => task.title);
// ["Read the lesson", "Build a counter", "Review examples"]

This is useful for shaping data for a display or another operation without changing the task objects. The output is a new array; for a normal dense array, it has one result for each input element.

Return the transformed value from the callback. A callback with braces needs an explicit return:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const labels = tasks.map(task => {
  return `${task.title} (${task.minutes} min)`;
});

Do not use map() merely to run an action and discard its result. MDN calls that an anti-pattern and recommends a side-effect-oriented loop such as forEach() or for...of instead: MDN’s map() reference.

Keep selected items with filter()

Use filter() when you need an array containing only items that pass a test. The callback is a predicate: a truthy result keeps that item; a falsy result excludes it.

const remainingTasks = tasks.filter(task => !task.complete);
// The two incomplete task objects

The result remains an array even if no items pass (then it is empty) or just one item passes. It is a shallow copy: the returned array is new, but its retained object elements are the same object references as in the original array.

Get one answer with find()

Use find() when you need the first item that passes a predicate, not an array of all matches:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const counterTask = tasks.find(task => task.title === "Build a counter");
// The matching task object, or undefined if none matches

The search stops at the first match. If no item passes, the result is undefined, so account for that before reading properties from the result:

if (counterTask) {
  console.log(counterTask.minutes);
}

Ask yes-or-no questions with some() and every()

Does at least one item pass?

some() returns true as soon as it finds a passing item; if none pass, it returns false. For example, an app could check whether any task is overdue:

const hasOverdueTask = tasks.some(task => task.overdue === true);

This example assumes the objects have an overdue property in the app’s actual data. The sample tasks above do not include one; add that field or replace the predicate with a property your data really has.

Do all visited items pass?

every() returns true if every visited item passes the predicate, and stops as soon as one fails. For example:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const allComplete = tasks.every(task => task.complete);
// false

A subtle consequence: every() returns true for an empty array because there is no item that fails the test. If the application requires at least one task as well as completion, combine the checks:

const hasTasksAndAllAreComplete = tasks.length > 0 && tasks.every(task => task.complete);

Both methods are predicate checks rather than ways to collect matches. See MDN’s every() reference for its behavior and examples.

Combine values with reduce()

Use reduce() when each callback call takes an accumulator, updates it, and returns the value to carry into the next call. To total estimated time, start with 0 and add each task’s minutes:

const totalMinutes = tasks.reduce((total, task) => {
  return total + task.minutes;
}, 0);
// 55

The initial value is the second argument to reduce(); here it makes the accumulator a number from the beginning and gives an empty list a sensible total of zero. Without an initial value, the first array element becomes the initial accumulator, which changes behavior for empty and one-element arrays. For beginner code, provide an explicit initial value suited to the result you are building.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The result need not be a number. Depending on the initial value and callback, the accumulator can be an object, array, string, or another kind of value. Because that flexibility can make a reducer harder to read, use it when combining data is genuinely clearer than a straightforward loop.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Map to zero or more results with flatMap()

Use flatMap() when each input should contribute an array of zero, one, or several results, and you want those results joined into one array with one level of flattening. For instance, collect all task tags:

const allTags = tasks.flatMap(task => task.tags);
// ["reading", "basics", "project", "basics"]

A task with an empty tag list contributes nothing. A callback can also choose to omit an item by returning [], or contribute a single result by returning a one-element array. This is conceptually a mapping followed by one-level flattening, not an unrestricted recursive flatten.

Combine methods when each step has a clear job

Named intermediate results make a sequence easy to inspect: first select incomplete tasks, then display their titles.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const openTasks = tasks.filter(task => !task.complete);
const openTaskTitles = openTasks.map(task => task.title);

Chaining can be concise when every step has a distinct purpose:

const openTaskTitles = tasks
  .filter(task => !task.complete)
  .map(task => task.title);

Keep the intermediate variables if they make the data shape or business rule easier to understand. A plain for...of loop can be clearer when the work involves several side effects, early exits, or complex control flow. The goal is code whose result and intent are obvious, not the most methods on one line.

One advanced detail: sparse arrays

A sparse array has empty slots, or “holes,” rather than a value at every index. Iterative methods do not all handle those slots identically. Methods including map(), filter(), and every() skip empty slots; methods including find() and includes() treat holes in ways that can make them behave like undefined for the relevant check. If code can receive sparse arrays, consult the specific method’s MDN behavior rather than assuming every method visits the same positions.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.