JavaScript Arrays the Functional Way: map, filter, reduce, find, sort and Object.entries
Four orders through map, filter, reduce, find, some, every, sort and Object.entries, traced one element at a time. Why [10, 9, 1].sort() gives [1, 10, 9], and what reduce does without a start value.
What you will learn
- Explain the one idea behind array methods: you write a small function and the method calls it per element
- Use map, filter and reduce, including reduce with a start value and an object accumulator
- Use find, some and every and know that they stop early
- Sort numbers correctly with a compare function and toSorted, and work on objects with Object.entries
Before you start
- JavaScript syntax: const, arrow functions, destructuring
Every example here uses the same four orders:
const orders = [
{ id: 1, item: "Keyboard", price: 50, paid: true },
{ id: 2, item: "Monitor", price: 200, paid: false },
{ id: 3, item: "Mouse", price: 25, paid: true },
{ id: 4, item: "Cable", price: 10, paid: true },
];
You give the function, the array calls it
Here's the one idea behind every method in this article. You write a very small function, say o => o.paid. You don't call it yourself. You hand it to an array method, and the method calls it for you, once per order. The answers come back true, false, true, true. What happens next depends on the method:
map: one in, one out
// map: one order in, one value out
const items = orders.map(o => o.item);
console.log(items);
// filter: keep the order when the arrow says true
const paid = orders.filter(o => o.paid);
console.log(paid.length, "of", orders.length, "paid");
console.log(paid[0] === orders[0]);
[ 'Keyboard', 'Monitor', 'Mouse', 'Cable' ]
3 of 4 paid
true
map passes the Keyboard order in as o, the arrow returns o.item, and that text goes into the first cell of a brand new array. Then the Monitor, the Mouse and the Cable. Four in, four out: map always returns the same number of elements, and it never changes orders.
The classic trap: write o => { o.item } with braces. Now the arrow is a block, and a block needs return, so every call returns undefined and you get four of them.
filter: keep it or drop it
filter also calls the arrow once per order, but treats the answer as a question: keep this one? The three paid orders go into a new array called paid and the Monitor is dropped. Then the third line asks something worth knowing: is paid[0] a copy? It prints true, so it's the very same Keyboard object. The array is new, but the objects inside are shared, not copied.
reduce: a running total
// sum starts at 0; each order adds its price
const total = orders.reduce(
(sum, o) => sum + o.price,
0);
console.log(total);
// acc starts as {}; each order adds 1 to a key
const counts = orders.reduce((acc, o) => {
const key = o.paid ? "paid" : "unpaid";
acc[key] = (acc[key] ?? 0) + 1;
return acc;
}, {});
console.log(counts);
285
{ paid: 3, unpaid: 1 }
Look at the 0 on its own line first: that's the start value, so sum starts at 0. Each call gets the result so far and the current order, and whatever the arrow returns becomes the new sum:
| Call | sum before | order price | returns |
|---|---|---|---|
| 1 | 0 | 50 (Keyboard) | 50 |
| 2 | 50 | 200 (Monitor) | 250 |
| 3 | 250 | 25 (Mouse) | 275 |
| 4 | 275 | 10 (Cable) | 285 |
Four orders in, one number out. Forget the start value and reduce uses the first element instead, so sum starts as the whole Keyboard object. An object plus a number turns into text, and the result is "[object Object]2002510". Always pass the start value.
The result doesn't have to be a number. The second reduce starts with {}. For the Keyboard, the key is "paid"; acc["paid"] doesn't exist yet, so ?? 0 uses 0 instead, and the count becomes 1. The arrow returns the same acc object for the next call. After all four orders: { paid: 3, unpaid: 1 }. The start value decides what you build.
find, some and every: they stop early
const big = orders.find(o => o.price > 100);
const none = orders.find(o => o.price > 500);
console.log(big.item, none);
let n = 0; // counts how often find calls the arrow
orders.find(o => { n++; return o.price > 100; });
console.log("checked", n, "of", orders.length);
// some: is ANY true? every: are ALL true?
console.log(orders.some(o => !o.paid));
console.log(orders.every(o => o.paid));
Monitor undefined
checked 2 of 4
true
false
find returns one element, not an array. It checks the Keyboard (50 is not over 100), then the Monitor (200 is), and stops right there. When nothing matches, as with a price above 500, it returns undefined. So check what find gave you before you use it: none.item throws TypeError: Cannot read properties of undefined (reading 'item').
The counter proves the early stop: the arrow ran only twice. some asks "is any order unpaid?" and stops at the Monitor with true. every asks "are all paid?" and one false is enough to stop with false.
sort: who goes first?
const byPrice = orders.toSorted(
(a, b) => a.price - b.price);
console.log(byPrice.map(o => o.item));
console.log(orders[0].item);
const nums = [10, 9, 1];
nums.sort(); // no compare: sorted as TEXT
console.log(nums);
nums.sort((a, b) => a - b);
console.log(nums);
[ 'Cable', 'Mouse', 'Keyboard', 'Monitor' ]
Keyboard
[ 1, 10, 9 ]
[ 1, 9, 10 ]
The compare function gets two orders, a and b, and returns a number. Negative means a goes first, positive means b goes first, zero leaves them. Keyboard against Monitor is 50 - 200 = -150, so Keyboard first. Mouse against Cable is 25 - 10 = 15, so Cable first. The result runs low to high, and orders[0] is still the Keyboard, because toSorted returns a sorted copy.
Then the surprise. With no compare function, sort turns every element into text and compares it like dictionary words: "10" starts with "1", which comes before "9". So [10, 9, 1] becomes [1, 10, 9]. And notice sort changed nums itself, in place. With (a, b) => a - b the numbers are compared as numbers and you get [1, 9, 10].
Objects go through pairs
// an object has no map or filter: work on its pairs
const stock = { keyboard: 12, mouse: 0, monitor: 3 };
const pairs = Object.entries(stock);
console.log(pairs);
const kept = pairs.filter(([name, qty]) => qty > 0);
const inStock = Object.fromEntries(kept);
console.log(inStock);
console.log(Object.keys(stock), Object.values(stock));
[ [ 'keyboard', 12 ], [ 'mouse', 0 ], [ 'monitor', 3 ] ]
{ keyboard: 12, monitor: 3 }
[ 'keyboard', 'mouse', 'monitor' ] [ 12, 0, 3 ]
An object has no map or filter; stock.filter(...) throws TypeError: stock.filter is not a function. Object.entries turns each key and value into a pair, giving an array that every array method works on. The filter takes each pair apart with [name, qty] and drops the mouse with 0. Object.fromEntries turns the pairs back into an object. Object.keys and Object.values give one side each.
A chain is a pipeline
const total = orders
.filter(o => o.paid) // 3 orders
.map(o => o.price) // [50, 25, 10]
.reduce((sum, p) => sum + p, 0); // 85
console.log("Paid total:", total);
Paid total: 85
Each step takes an array and hands a new one to the next: three paid orders, then [50, 25, 10], then 0 + 50 + 25 + 10 = 85. The original orders never changes. Flip o.paid to !o.paid and you add up the unpaid order instead, 200.
Quick recap
| Method | Gives back | Watch out for |
|---|---|---|
map | new array, same length | braces need return |
filter | new array, maybe shorter | the same objects inside, not copies |
reduce | one value | always pass the start value |
find | first match or undefined | check before using it; stops early |
some / every | true or false | stop as soon as the answer is known |
sort / toSorted | sorted in place / sorted copy | numbers need (a, b) => a - b |
Object.entries | array of [key, value] pairs | fromEntries goes back |
If you know Python, these map closely onto list comprehensions, sum(), any(), all(), sorted() and dict.items(); the main difference is that you pass the function to a method on the array.
Try it yourself
Using the same orders, build { paid: 85, unpaid: 200 } with a single reduce. Then sort the items by name with toSorted and confirm orders is unchanged.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
One Request, Two Answers: the Same Post as an HTML Page and as JSON
Ask a Django blog for the same post twice: once as a 12,731-byte HTML page built by a template, once as 2,976 bytes of JSON built by a serializer. Compare the headers, see who builds the page, and why the server still owns every write.
A Blog Design from a Prompt: Downloading Figma Make Code and Reading App.tsx and BlogCard.tsx
Make a blog design from a prompt in Figma Make, download src.zip, unzip it with Python's zipfile module, and read the two files that matter: App.tsx with its selectedPost state and BlogCard.tsx with its props.
How a Web Page Works: HTML Tags, Elements and Attributes
A web page is a text file full of labelled pieces. Learn tags, attributes and nesting with three tiny pages, and see what breaks when an attribute or a closing tag is wrong.
Semantic HTML: header, nav, main, aside and footer as Page Landmarks
The same page written as div soup and with semantic tags looks identical, but only one gives screen readers and search engines landmarks and an outline. Plus tables, div, span and the one-main rule.
