LESSON 18 · BEGINNER4 min read

Array Methods: map, filter, reduce

Transform lists with callbacks and choose the right array method for each job.

ES2024 / Node.js 20+Free to readModule 4 of 19
YOUR NEXT SMALL WINS

By the end, you’ll be able to…

  • Read callback signatures and return values for common array methods.
  • Transform, select, and fold data with map, filter, and reduce.
  • Chain methods safely and avoid mutation traps such as sort.

01Callbacks receive value, index, and array

map, filter, and several other array methods accept a callback. The callback is called once per item and receives the value, the index, and the whole array. Beginners usually need only the value; name the extra parameters when you use them. The method decides what to do with the callback's return value.

map builds a new array from whatever the callback returns. filter builds a new array from the original items for which the callback returns a truthy value. Neither method changes the original array, although the callback can mutate objects if you write it that way. Keep callbacks free of side effects when possible.

callback-arguments.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

02Transform with map and select with filter

Use map when the output has one item for every input item. The new array always has the same length. Returning an object is fine; returning undefined leaves an undefined entry, which is usually a sign that filter belongs first. A map callback that returns nothing is almost always a mistake, because the caller receives a new array full of holes in meaning.

Use filter when you need a subset. The callback should answer one yes-or-no question. Keep the original objects intact unless the task explicitly asks for a transformation. Chaining filter then map is often clearer than doing both jobs in one callback. If the test depends on position, use the index argument deliberately.

filter-then-map.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

03Fold a list with reduce

reduce turns a list into one value. It takes a callback and an initial accumulator. The callback receives the accumulator and the current item, and returns the next accumulator. Always pass an initial value for beginner code: without one, reduce uses the first item and throws on an empty array.

The accumulator can be a number, string, array, or object. Return a new accumulator instead of mutating shared state when you can. Name the parameters total and item, or counts and entry, so the fold reads like a sentence. If the callback becomes long, move it into a named function. When the accumulator is an object, spread it before adding a key so each step returns a fresh value.

reduce.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

04Find one, test many, and chain with care

find returns the first matching item or undefined; findIndex returns its position or -1. some asks whether at least one item matches, and every asks whether all do. These methods stop early when the answer is known, which can be more efficient than filtering and checking length. Use find when there should be one answer and filter when there may be many. Choose by the shape of the result: one transformed item per input, a subset, one accumulated value, or a single match.

Chains run left to right. Put the cheapest and most selective step first when it does not change the result. Be careful with sort: it mutates and compares strings by default, so [2, 10] sorts as [10, 2]. Use toSorted with a numeric comparator, or copy before sorting. When in doubt, log the array before and after a chain to see which step changed it.

search-and-test.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
LET IT CLICK

The ideas worth keeping.

  • map transforms every item, filter selects items, and reduce folds a list into one value.
  • Callbacks receive the value, index, and array, and their return value drives the method.
  • Chain small steps and avoid mutation traps such as sort reordering the original array.
TURN UNDERSTANDING INTO SOMETHING YOU CAN DO

Make it yours.

Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.

01

Exercise 1: Names of adult users

Given an array of user objects with name and age, write adultNames(users) that returns the names of users aged 18 or older. Keep the original order and do not mutate the input.

your_turn_1.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.jsJavaScript
const users = [  { name: 'Ada', age: 34 },  { name: 'Lin', age: 17 },  { name: 'Sam', age: 22 },];function adultNames(people) {  return people    .filter(person => person.age >= 18)    .map(person => person.name);}console.log(adultNames(users));console.log(users.length);

filter keeps Ada and Sam, then map turns those objects into names. Both methods return new arrays, so users is untouched. The output is [ 'Ada', 'Sam' ] followed by 3.

02

Exercise 2: Total by category

Write totalByCategory(items) that reduces an array of { category, total } objects into one object containing the summed total for each category. Do not modify the input objects. Test it with books at 30 and 15, and tools at 22.

your_turn_2.js⚡JavaScript
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.jsJavaScript
function totalByCategory(items) {  return items.reduce((totals, item) => {    const key = item.category;    return {      ...totals,      [key]: (totals[key] ?? 0) + item.total,    };  }, {});}const orders = [  { category: 'books', total: 30 },  { category: 'books', total: 15 },  { category: 'tools', total: 22 },];console.log(totalByCategory(orders));

The initial accumulator is an empty object. Each step spreads the previous totals into a fresh object and writes the updated category value. The result is { books: 45, tools: 22 }, and the orders array is unchanged.

A SMALL QUESTION. A USEFUL NEXT STEP.

What stayed with you?

Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.

A LITTLE ACTIVE RECALL0 / 3 answered
01What does filter use to decide whether an item appears in the result?
02Why pass 0 as the initial value to reduce when summing an array of numbers?
03Which statement about sort is correct?
⚡CODING CHALLENGE
🔒Required to Mark Lesson Complete

Exercise 1: Names of adult users

Given an array of user objects with name and age, write adultNames(users) that returns the names of users aged 18 or older. Keep the original order and do not mutate the input.

EXPECTED OUTPUT
["Ada","Sam"]
3
main.jsJavaScript
Ctrl + ↵
Execution Console
Click "Run & Verify" (or press Ctrl + Enter) to test your code against the challenge.

Keep exploring.

The official references behind this lesson, when you want a second angle or the full details.

One lesson closer.

Reading is a start. Trying it yourself makes the connection.

Solve the hands-on coding challenge in the knowledge section to verify your code and unlock lesson completion.