Array methods: map, filter, find and reduce
Course contents (16 lessons)
- Getting started
- What is JavaScript and where does it run?
- Variables with let and const
- Values and operators
- Data types: numbers, strings, booleans, null and undefined
- Operators: arithmetic, comparison and logical
- Strings and template literals
- Making decisions and repeating work
- Conditionals: if, else and switch
- Loops: for, while and for...of
- Functions
- Functions: declarations, parameters and return values
- Arrow functions and callbacks
- Arrays and objects
- Arrays: creating, reading and changing lists
- Array methods: map, filter, find and reduce
- Objects: properties, methods and copying
- Scope and the browser
- Scope and closures, gently
- The DOM: selecting and changing elements
- Events: reacting to clicks, input and forms
- Final project
- 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 want | Use |
|---|---|
| A new list, same length, changed items | map |
| A new list with fewer items | filter |
| One item | find |
| A yes or no answer | some, every, includes |
| One value from many (sum, count, grouping) | reduce |
| Just to do something for each | forEach 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 ofundefined. - Expecting filter to return one item. It always returns an array, even if only one item matches. Use
findfor a single item. - Mutating inside map. Changing
p.price = 0insidemapalters the original objects. Return a new object with spread instead. - No starting value for reduce. Always pass one.
Try it yourself
- From
[1, 2, 3, 4, 5, 6], get the squares of the even numbers only. - From the products list, find the average price of the items in stock.
- Use
reduceto 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 }. - Check whether any product costs more than 20000 and whether all are in stock.
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