Filter & Sort Lists Filtering and Sorting Lists

Last updated: 2026-11-02

Filter & Sort Lists Filtering and Sorting Lists

Filtering and sorting a list does not mutate the original array; instead you derive a new one with filter, sort and similar methods and render that. Keeping the source data untouched and computing the view at render time is the core idea behind React's approach to lists. It also avoids the classic bug where sorting a state array silently corrupts it.

GroupRendering & State
KindPattern
SinceEarliest React versions

ℹ️ Info The editor transpiles JSX to JavaScript and renders the real UI in a sandbox; components mount automatically — no manual render call needed.

📝 Syntax

const shown = products
  .filter((p) => p.price < 100)        // Filter → a new array
  .sort((a, b) => a.price - b.price)   // Sort (on the copy produced by filter)
{shown.map((p) => <li key={p.id}>{p.name}</li>)}

Returns:No return value — a coding convention and mental model.

▶ Example

The example runs out of the box: it auto-renders when expanded, and edits take effect instantly.

Output:

A product list with two controls: ticking "Under 100 only" leaves just the mouse, and clicking the price button switches between descending and ascending order while the list reorders live — the original array is never modified.

💡 Key Points

💡 Tip Filter before you sort: filter returns a new array, so sorting that copy in place never touches the state array.
⚠️ Warning sort mutates the array! Copy it with [...arr] — or filter it first — before sorting a state array directly.
ℹ️ Info The filter conditions and the sort direction normally live in state, while the displayed result is computed during render, so there is no need to store a separate "derived state".
More case studies coming soon.

📚 Related Tutorials

❓ FAQ

Q How do I filter and sort a list in React?
A Filter and sort the data before rendering to get a new array, then map it into JSX. Keep the filter conditions in state and compute the result during render.
Q Does sort modify the original array?
A Yes, sort sorts in place. You must copy a React state array before sorting it ([...arr].sort, or filter first), otherwise the state array is corrupted.
Q Should the filtered result be stored in state?
A No. The filtered result is derived from the original data plus the conditions, so compute it during render; storing a second copy easily leaves two versions out of sync.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏