Sub topic 13
Beyond the Big Three: flatMap, find, some, every, and reduceRight
This chapter assumes you already know how map, filter, and reduce work, how to chain them, and what arguments a callback receives. It covers five related methods. Each one handles a common job more directly than the big three, and sometimes with less work.
flatMap: Map, Then Flatten One Level
flatMap runs a callback on each element, the same way map does. It then flattens the result by one level. Use it when each input element should produce zero, one, or several output elements.
const sentences = ['hello world', 'map filter'];
console.log(sentences.flatMap(s => s.split(' ')));
// ['hello', 'world', 'map', 'filter']
// Returning [] drops an element, and returning [a, b] expands it
const result = [1, 2, 3, 4].flatMap(n => (n % 2 === 0 ? [n, n] : []));
console.log(result); // [2, 2, 4, 4]
// Only one level is flattened
console.log([[1, [2]]].flatMap(x => x)); // [1, [2]]In the second example, flatMap does the work of a filter and a map in one pass. It does not flatten deeper levels. For deeper nesting, use flat(depth).
find and findIndex: Stop at the First Match
filter always visits every element and returns an array. If you only need the first match, find returns that element and stops looking. If nothing matches, it returns undefined. findIndex returns the position instead, or -1 when nothing matches.
const nums = [3, 8, 12];
console.log(nums.find(n => n > 5)); // 8
console.log(nums.find(n => n > 100)); // undefined
console.log(nums.findIndex(n => n > 5)); // 1some and every: Yes-or-No Questions
some returns true if at least one element passes the predicate. every returns true only if all elements pass. Both short-circuit: some stops at the first true, and every stops at the first false.
let calls = 0;
const big = [3, 8, 12, 20].some(n => {
calls++;
return n > 10;
});
console.log(big, calls); // true 3
console.log([3, 8, 12].every(n => n > 0)); // true
// Empty arrays
console.log([].some(n => n > 0)); // false
console.log([].every(n => n > 0)); // truePeople often expect [].every(...) to return false, but it returns true. The reason is that no element fails the test. If an empty list should count as a failure in your logic, check arr.length > 0 && arr.every(...).
Avoid writing filter(...).length > 0. It builds an array you then throw away, and it can't stop early.
reduceRight: Fold From the End
reduceRight works like reduce, but it walks from the last element to the first. The same rules for initial values and empty arrays apply.
console.log(['a', 'b', 'c'].reduceRight((acc, s) => acc + s, '')); // 'cba'
// Compose functions right to left: compose(f, g)(x) === f(g(x))
const compose = (...fns) => x => fns.reduceRight((acc, fn) => fn(acc), x);
const addOne = n => n + 1;
const double = n => n * 2;
console.log(compose(addOne, double)(5)); // 11Order only matters when the operation is not commutative, for example string concatenation or function composition.
Choosing the Right Method
| You want | Use | Returns |
|---|---|---|
| Zero or more outputs per element | `flatMap` | New array |
| The first matching element | `find` | Element or `undefined` |
| The position of the first match | `findIndex` | Index or `-1` |
| Whether any element matches | `some` | Boolean |
| Whether all elements match | `every` | Boolean |
| A fold from the end | `reduceRight` | Accumulator |
Exercise
Rewrite users.filter(u => u.isAdmin).length > 0 with a better method, and explain why it is better. What does your version return for an empty users array?
Show answer
Use users.some(u => u.isAdmin). It stops at the first admin and does not build a throwaway array. For an empty array it returns false, which matches the original expression.
Exercise
Given const tags = [['js', 'web'], [], ['node']], produce ['JS', 'WEB', 'NODE'] in a single method call.
Show answer
tags.flatMap(group => group.map(t => t.toUpperCase())). The inner map uppercases each group, and flatMap flattens the groups one level, so the empty group adds nothing.