Sub topic 13
Beyond the Big Three: flatMap, find, some, every, and reduceRight
You can now build most transformations with map, filter, and reduce. Some jobs fit those three poorly. You might reach for reduce to answer a yes/no question, or write filter(...)[0] to get one item. Both work, but they say less than they could and often do more work than they need to. JavaScript has more specific methods for these jobs.
This chapter assumes you are comfortable with arrow functions, the callback arguments (element, index, array), and how reduce uses an accumulator and an initial value. The examples run in any modern browser or in Node.js 18 or later. findLast and findLastIndex need Node.js 18+ or a 2022-or-later browser.
Choosing the Right Method
Start with the question you are asking of the array. The method follows from the answer.
flatMap: Map, Then Flatten One Level
flatMap calls your callback on each element, the same way map does, and then flattens the result by exactly one level. If the callback returns an array, flatMap spreads that array's items into the output. If it returns anything else, flatMap adds that value as is.
const sentences = ['hello world', 'map filter'];
console.log(sentences.map(s => s.split(' ')));
// [['hello', 'world'], ['map', 'filter']]
console.log(sentences.flatMap(s => s.split(' ')));
// ['hello', 'world', 'map', 'filter']A common use is pulling nested collections out of records, such as every line item across a set of orders:
const orders = [
{ id: 1, items: ['pen', 'ink'] },
{ id: 2, items: [] },
{ id: 3, items: ['paper'] }
];
const allItems = orders.flatMap(order => order.items);
console.log(allItems); // ['pen', 'ink', 'paper']flatMap as filter and map in one pass
Each callback call can return zero, one, or several items, so flatMap can filter and transform in the same pass. Return [] to drop an element and [value] to keep a transformed one.
const raw = ['4', 'oops', '10', ''];
const doubled = raw.flatMap(s => {
if (s.trim() === '') return [];
const n = Number(s);
return Number.isNaN(n) ? [] : [n * 2];
});
console.log(doubled); // [8, 20]This is useful when the check and the transformation share work, as with Number(s) here. When they don't share work, filter(...).map(...) is usually easier to read.
Gotcha: only one level
flatMap does not flatten recursively, and it has no depth argument. For deeper nesting, use map followed by flat(depth).
const nested = [[1], [2, [3]]];
console.log(nested.flatMap(x => x)); // [1, 2, [3]]
console.log(nested.map(x => x).flat(2)); // [1, 2, 3]find and findIndex: The First Match
find returns the first element for which your predicate is truthy and then stops. If nothing matches, it returns undefined. findIndex returns that element's position instead, or -1 if nothing matches.
const users = [
{ id: 7, name: 'Ada' },
{ id: 9, name: 'Grace' },
{ id: 12, name: 'Linus' }
];
console.log(users.find(u => u.id === 9)); // { id: 9, name: 'Grace' }
console.log(users.find(u => u.id === 99)); // undefined
console.log(users.findIndex(u => u.id === 12)); // 2
console.log(users.findIndex(u => u.id === 99)); // -1Prefer find to filter(...)[0]. filter checks every element and builds a whole array that you then throw away. find stops at the first match.
Gotcha: when undefined is a real value
When find returns undefined, it could mean "no match" or "the matching element was undefined". If your array can hold undefined, use findIndex and check for -1. Sparse arrays show the difference. find and findIndex visit holes as if they held undefined, but some, every, map, filter, and reduce skip holes.
const sparse = [, 1]; // index 0 is a hole
console.log(sparse.find(x => x === undefined)); // undefined (match or miss?)
console.log(sparse.findIndex(x => x === undefined)); // 0 (clearly a match)
console.log(sparse.some(x => x === undefined)); // false (hole skipped)findLast and findLastIndex
To search from the end, use findLast and findLastIndex (ES2023). Before these existed, people often wrote [...arr].reverse().find(...), which copies the array.
const events = [
{ type: 'login', at: 1 },
{ type: 'click', at: 2 },
{ type: 'login', at: 3 }
];
console.log(events.findLast(e => e.type === 'login')); // { type: 'login', at: 3 }
console.log(events.findLastIndex(e => e.type === 'login')); // 2some 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 always return a real boolean, even when your predicate returns other truthy or falsy values.
const nums = [3, 8, 12];
console.log(nums.some(n => n > 10)); // true
console.log(nums.every(n => n > 0)); // true
console.log(nums.every(n => n > 5)); // falseShort-circuiting
Both methods stop as soon as they know the answer. some stops at the first true, and every stops at the first false. You can see this by counting calls:
let checks = 0;
const hasBig = [3, 8, 12, 20].some(n => {
checks++;
return n > 5;
});
console.log(hasBig, checks); // true 2
checks = 0;
const allSmall = [3, 8, 12, 20].every(n => {
checks++;
return n < 5;
});
console.log(allSmall, checks); // false 2A reduce that returns a boolean can't stop early, so it checks all four elements. Short-circuiting also matters when the predicate is expensive or has side effects. Don't count on later elements being visited.
Gotcha: empty arrays
On an empty array, some returns false and every returns true. In logic this is called vacuous truth: no element fails, so "all of them pass" holds.
console.log([].some(x => x > 0)); // false
console.log([].every(x => x > 0)); // trueThis can cause real bugs. A check like "every uploaded file is under 5 MB" passes when no files were uploaded. If an empty list should fail, test for it directly:
const files = [];
const valid = files.length > 0 && files.every(f => f.size < 5_000_000);
console.log(valid); // falsereduceRight: Folding from the End
reduceRight works like reduce but visits elements from the last index to the first. It follows the same initial-value rules: with no initial value, an empty array throws a TypeError.
console.log(['a', 'b', 'c'].reduceRight((acc, s) => acc + s, '')); // 'cba'
try {
[].reduceRight((acc, s) => acc + s);
} catch (err) {
console.log(err instanceof TypeError); // true
}The classic use is function composition. Mathematically, compose(f, g, h)(x) means f(g(h(x))), so the right-most function must run first:
const compose = (...fns) => x => fns.reduceRight((acc, fn) => fn(acc), x);
const trim = s => s.trim();
const upper = s => s.toUpperCase();
const exclaim = s => s + '!';
const shout = compose(exclaim, upper, trim);
console.log(shout(' hi ')); // 'HI!'When order doesn't matter, as with summing numbers, reduceRight adds nothing over reduce. Use it only when right-to-left order is part of the meaning.
Quick Reference
| Method | Returns | Stops early? | On an empty array |
|---|---|---|---|
| `flatMap(fn)` | New array, flattened one level | No | `[]` |
| `find(fn)` | First matching element or `undefined` | Yes | `undefined` |
| `findIndex(fn)` | Index of first match or `-1` | Yes | `-1` |
| `findLast(fn)` | Last matching element or `undefined` | Yes | `undefined` |
| `some(fn)` | `true` if any element matches | Yes, on first `true` | `false` |
| `every(fn)` | `true` if all elements match | Yes, on first `false` | `true` |
| `reduceRight(fn, init)` | Accumulated value, right to left | No | `init`, or `TypeError` with no `init` |
Exercises
Exercise
You have const tags = ['js, web', 'node', '', 'css, web']. Write one flatMap call that produces ['js', 'web', 'node', 'css', 'web']. Split on commas, trim each piece, and drop empty strings.
Show answer
tags.flatMap(t => t.split(',').map(s => s.trim()).filter(s => s !== '')). For '', split(',') returns [''], and the inner filter removes it. flatMap then flattens each inner array into the result.
Exercise
A form validator runs fields.every(f => f.value !== '') and reports success even when the user hasn't added any fields. Why, and how do you fix it?
Show answer
every returns true for an empty array (vacuous truth), because no element fails the predicate. If an empty list should be invalid, add a length check: fields.length > 0 && fields.every(f => f.value !== '').
Exercise
Given const log = [{ level: 'warn', msg: 'a' }, { level: 'error', msg: 'b' }, { level: 'error', msg: 'c' }], how do you get the most recent error's message without copying or reversing the array? What does your expression return if no error exists?
Show answer
log.findLast(e => e.level === 'error')?.msg returns 'c'. If no error exists, findLast returns undefined, and optional chaining makes the whole expression undefined instead of throwing.
Exercise
Using compose from this chapter, what does compose(x => x * 2, x => x + 3)(4) return, and why would reduce give a different answer?
Show answer
It returns 14. reduceRight applies x + 3 first, giving 7, and then x * 2, giving 14. With reduce, the functions run left to right: 4 * 2 = 8, then 8 + 3 = 11.