Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

React
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • A Blog Design from a Prompt: Downloading Figma Make Code and Reading App.tsx and BlogCard.tsx
  • How a Web Page Works: HTML Tags, Elements and Attributes
  • Semantic HTML: header, nav, main, aside and footer as Page Landmarks
  • HTML Forms: Labels, Names, Input Types and Where the Data Goes (GET vs POST)
  • CSS Basics: Selectors, Which Rule Wins, and the Box Model
  • CSS Flexbox vs Grid: A Nav Bar, a Card Row and a Dashboard
  • Responsive CSS: Viewport, Mobile-First Media Queries, clamp() and Dark Mode with Tokens
  • JavaScript for People Who Already Code: Syntax, Modules and Five Surprises
  • JavaScript Arrays the Functional Way: map, filter, reduce, find, sort and Object.entries
  • Async JavaScript: Promises, async/await, fetch and Promise.all
  • JavaScript in the Page: the DOM, querySelector and Events
  • npm, package.json and Vite: What npm install Fetches and How Vite Serves and Builds Your Page
  • TypeScript Essentials: Types Checked, Then Erased (Interfaces, Unions, Generics)
  • Why React, JSX and Components: The Page as a Function of Data
  • React Props and Composition: Data Down, Calls Up, Children in the Slot
  • Routing With React Router: One Page, Many Addresses
  • React Component Tests With Vitest and Testing Library: Test What the User Sees
  • End-to-End Tests for a React App With Playwright: A Full Dress Rehearsal
  • Why AI-Built Websites All Look the Same, and Four Levels That Fix It
  • Visual Hierarchy, Spacing and the 8-Point Grid: Tell the Eye What to Read First
  • Colour, Contrast and Dark Palettes: 60-30-10, Semantic Tokens and Ratios You Can Compute
  • Typography That Sells: Type Scale, Line Length and Free Font Pairings
  • The UI Element Catalogue: Buttons to Toasts, Their Jobs, States and shadcn/ui Names
  • Design Tokens: Primitive and Semantic Tokens, from Figma to CSS to Tailwind
  • Tailwind CSS 4 in React: Utility Classes, Responsive Prefixes, Hover and Dark Mode
  • shadcn/ui in React: Components You Own, Edit and Commit
  • Design Tokens to a Tailwind Theme: Light and Dark Mode with @theme inline
  • Motion in React: Entrance, Hover, Exit and Layout Animations
  • A React Dashboard: Stat Cards, a Recharts Line Chart and a Sortable Table
  • Accessibility in Practice: Dialogs, Menus and the Keyboard in React
  • Reference-Driven Design: Extract a DESIGN.md From a Site You Admire and Build From It
  • Components, Variants and Variables: One Design System in Figma and in CSS
  • Figma MCP Server: Build a React Component From a Frame, Then Write It Back
  • Claude Design: From a Brief to a Clickable Prototype, Then Hand It Off to Claude Code
  • Critiquing AI-Generated UI: Six Checks for Every Screen
  • The AI Design Landscape: Prompt to UI, Prompt to App, and Design to Code
  • Your Brand Rules Folder: One Folder Every AI-Built Page Follows
  • The Best-Practice UI Prompt: Plain Sentences That Beat the Average AI Page
  • UI Ideas From Figma Make, Google Stitch and ChatGPT: One Prompt, Three Designs
  • Google Stitch From a Sketch or Screenshot: Show the Layout, Say What to Keep
  • Stitch to Figma to Code: Turn a Stitch Screen Into Code That Uses Your Tokens
  • Figma Make: Prompt to Prototype With a Four-Part Prompt
  • Upgrade a Dated UI From One Screenshot (or a Reference Image)
  • States and Feedback: Make Every Click Get an Answer
  • A Design-Loop Skill: Claude Screenshots, Scores and Fixes Its Own UI
  • Copy Without the AI Tells: A Copy Pass on a Landing Page
  • React State, Events, Lists and Conditional Rendering: Follow One Click
  • React useEffect: When It Runs, What Cleanup Is For, and When You Don't Need One
  • Lifting State Up, Refs and React DevTools: Put State Where It Is Needed
  • Forms and Actions in React 19: Controlled Inputs, Form Actions, useActionState and useFormStatus
  • React Context and Custom Hooks: Share One Value, Reuse the Logic
  • Server State With TanStack Query: One Key, One Request, One Cache
  • Mutations and Optimistic Updates in TanStack Query: Change Data, Then Tell the Cache
  • Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval
  • A Mock Backend in the Browser With Mock Service Worker, Generated From the Spec
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • Forms With React Hook Form and Zod: The API's Rules in the Browser, the Server's Errors Under the Field
  • JWT Auth in a React Client With a FastAPI Backend: Log In, Carry the Token, Let the Server Decide
  1. Blog
  2. /
  3. React
  4. /
  5. Fundamentals

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Fundamentals

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:

The function o => o.paid answers true, false, true, true for the four orders. map collects all answers, filter keeps the three true orders, find returns the first true one, some says true, every says false. KeyboardMonitorMouseCable o => o.paid truefalsetruetrue map [true, false, true, true] filter [Keyboard, Mouse, Cable] find Keyboard (stops at first true) some true (is any true?) every false (are all true?) same function, five different results
You write the small function; the method does the loop and decides what to do with the answers.

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:

Callsum beforeorder pricereturns
1050 (Keyboard)50
250200 (Monitor)250
325025 (Mouse)275
427510 (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

MethodGives backWatch out for
mapnew array, same lengthbraces need return
filternew array, maybe shorterthe same objects inside, not copies
reduceone valuealways pass the start value
findfirst match or undefinedcheck before using it; stops early
some / everytrue or falsestop as soon as the answer is known
sort / toSortedsorted in place / sorted copynumbers need (a, b) => a - b
Object.entriesarray of [key, value] pairsfromEntries 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in React · 10 of 59

Previous
JavaScript for People Who Already Code: Syntax, Modules and Five Surprises
Next post
Async JavaScript: Promises, async/await, fetch and Promise.all

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.

On this page

  • You give the function, the array calls it
  • map: one in, one out
  • filter: keep it or drop it
  • reduce: a running total
  • find, some and every: they stop early
  • sort: who goes first?
  • Objects go through pairs
  • A chain is a pipeline
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.