Course progress0%
Course content
45 min

Choose the Array Method from the Result

Use map, filter, find and forEach for distinct application intentions

By the end of this lesson

  • Select an array method from the required result
  • Avoid forcing every method into one feature

Ask what result you need

Do not choose an array method because a requirement lists its name. Choose it from the result the application needs.

Begin with an ordinary sentence. Then choose the method:

  • "I need all matching items" means filter.
  • "I need one matching item" means find.
  • "I need to convert every item" means map.
  • "I need to do something once for every item" means forEach.
Method Question Result
filter() Which elements match? A new array, possibly empty
find() What is the first matching element? One element or undefined
map() What should each element become? A new array of the same length
forEach() What side effect should happen for each element? undefined

Four intentions in the resource library

const availableResources = state.items.filter((item) => item.available);

Use filter because several resources may match.

const selectedResource = state.items.find((item) => item.id === state.selectedId);

Use find because one id should identify one resource.

const titles = state.items.map((item) => item.title);

Use map because every resource becomes one title.

state.items.forEach((item) => {
  console.log(`${item.id}: ${item.title}`);
});

Use forEach when performing an action for every item and no result array is needed.

Choose before coding

Select a method for each need:

  1. Obtain all resources lasting less than 20 minutes.
  2. Obtain the resource whose id is 3.
  3. Produce an array of topic names.
  4. Add one DOM element for every resource.

The answers are filter, find, map and forEach. A for...of loop may also be clearer for DOM creation, especially when several statements are required.

If the choice remains difficult, write the expected result first. Is it an array, one object, a transformed array or no returned collection? The shape of the answer usually reveals the method.

A common map mistake

const result = state.items.map((item) => {
  console.log(item.title);
});

result becomes an array of undefined values because the callback returns nothing. Use forEach for logging, or return the transformed value from map.

What to remember

filter selects many, find selects one, map transforms every element and forEach performs an effect. The required result should determine the method.

Lesson complete?

Your progress is saved on this device.