Tutorials / JavaScript Fundamentals / Array methods: map, filter, find and reduce

Array methods: map, filter, find and reduce

15 min read javascript
Course contents (16 lessons)
  1. Getting started
  2. What is JavaScript and where does it run?
  3. Variables with let and const
  4. Values and operators
  5. Data types: numbers, strings, booleans, null and undefined
  6. Operators: arithmetic, comparison and logical
  7. Strings and template literals
  8. Making decisions and repeating work
  9. Conditionals: if, else and switch
  10. Loops: for, while and for...of
  11. Functions
  12. Functions: declarations, parameters and return values
  13. Arrow functions and callbacks
  14. Arrays and objects
  15. Arrays: creating, reading and changing lists
  16. Array methods: map, filter, find and reduce
  17. Objects: properties, methods and copying
  18. Scope and the browser
  19. Scope and closures, gently
  20. The DOM: selecting and changing elements
  21. Events: reacting to clicks, input and forms
  22. Final project
  23. Project: build a to-do list in the browser

Doing more with less code

In the loops lesson we processed arrays with for loops. That works, but for common tasks arrays have built-in methods that say what you want more clearly. Each of these takes a callback function, which is why we learned arrow functions first.

Our sample data for this lesson is a list of products:

const products = [
  { name: "Keyboard", price: 3500, inStock: true },
  { name: "Mouse", price: 1200, inStock: true },
  { name: "Monitor", price: 28000, inStock: false },
  { name: "Cable", price: 400, inStock: true },
];

Each item is an object with properties. We cover objects in the next lesson, but you can already read these: product.price gives the price.

forEach: do something for each item

products.forEach(product => {
  console.log(`${product.name}: Rs. ${product.price}`);
});

forEach runs the callback once per item and returns nothing. It is a simple replacement for a for...of loop when you just want side effects like printing.

map: transform every item

map builds a new array of the same length, where each item is the result of the callback.

const names = products.map(p => p.name);
console.log(names); // ["Keyboard", "Mouse", "Monitor", "Cable"]

const withTax = products.map(p => ({ ...p, price: p.price * 1.17 }));

The original array is not changed. In the second example, { ...p, price: ... } copies all properties of p and replaces the price. Use map when you want to turn one list into another list.

filter: keep some items

filter returns a new array with only the items for which the callback returns true.

const available = products.filter(p => p.inStock);
const cheap = products.filter(p => p.price < 2000);

console.log(available.length); // 3
console.log(cheap.map(p => p.name)); // ["Mouse", "Cable"]

find and findIndex

find returns the first matching item, or undefined if none matches. findIndex returns the position, or -1.

const monitor = products.find(p => p.name === "Monitor");
console.log(monitor.price); // 28000

const missing = products.find(p => p.name === "Printer");
console.log(missing); // undefined

Use find when you want one item, and filter when you want all of them. Always check for undefined before reading properties from the result.

some and every

console.log(products.some(p => !p.inStock));   // true, at least one is out of stock
console.log(products.every(p => p.price > 100)); // true, all pass

They return a boolean and stop as soon as the answer is known.

reduce: combine into one value

reduce is the one people find hardest, so let me go slowly. It walks through the array and keeps a running result, called the accumulator. For each item, your callback gets the accumulator and the item, and returns the new accumulator. You give it a starting value as the second argument.

const products = [
  { name: "Keyboard", price: 3500, inStock: true },
  { name: "Mouse", price: 1200, inStock: true },
  { name: "Monitor", price: 28000, inStock: false },
  { name: "Cable", price: 400, inStock: true },
];

const total = products.reduce((sum, p) => sum + p.price, 0);
console.log(total); // 33100

const inStockTotal = products
  .filter(p => p.inStock)
  .reduce((sum, p) => sum + p.price, 0);
console.log(inStockTotal); // 5100

const names = products
  .filter(p => p.inStock)
  .map(p => p.name)
  .sort();
console.log(names); // ["Cable", "Keyboard", "Mouse"]

Step by step, the first reduce starts with sum = 0. Item one adds 3500, giving 3500. Item two adds 1200, giving 4700. Item three adds 28000, and item four adds 400. The final value, 33100, is returned.

Always give reduce a starting value. Without one, it uses the first item as the start, and an empty array will throw an error.

Chaining

Because map and filter return arrays, you can chain them, as in the last example. Read it top to bottom: keep the products in stock, take their names, sort them. Each step is small, and the whole thing reads like a recipe.

A word of balance. Chains are lovely until they get long. If a chain needs more than three or four steps, I split it into named variables so I can print each stage while debugging.

Choosing the right method

You wantUse
A new list, same length, changed itemsmap
A new list with fewer itemsfilter
One itemfind
A yes or no answersome, every, includes
One value from many (sum, count, grouping)reduce
Just to do something for eachforEach or for...of

Common mistakes

  • Using map when you do not use the result. If you only want side effects, use forEach.
  • Forgetting to return. A callback with braces needs return: map(p => { p.price }) gives an array of undefined.
  • Expecting filter to return one item. It always returns an array, even if only one item matches. Use find for a single item.
  • Mutating inside map. Changing p.price = 0 inside map alters the original objects. Return a new object with spread instead.
  • No starting value for reduce. Always pass one.

Try it yourself

  1. From [1, 2, 3, 4, 5, 6], get the squares of the even numbers only.
  2. From the products list, find the average price of the items in stock.
  3. Use reduce to count how many times each word appears in ["a", "b", "a", "c", "a", "b"]. The result should be an object like { a: 3, b: 2, c: 1 }.
  4. Check whether any product costs more than 20000 and whether all are in stock.
javascript
const products = [
  { name: "Keyboard", price: 3500, inStock: true },
  { name: "Mouse", price: 1200, inStock: true },
  { name: "Monitor", price: 28000, inStock: false },
  { name: "Cable", price: 400, inStock: true },
];

const total = products.reduce((sum, p) => sum + p.price, 0);
console.log(total); // 33100

const inStockTotal = products
  .filter(p => p.inStock)
  .reduce((sum, p) => sum + p.price, 0);
console.log(inStockTotal); // 5100

const names = products
  .filter(p => p.inStock)
  .map(p => p.name)
  .sort();
console.log(names); // ["Cable", "Keyboard", "Mouse"]

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account