Back to JavaScript Performance

Use Loop for Min/Max Instead of Sort

javascriptarraysperformancesortingalgorithms
28.0k🕒 2026-06-10Source ↗

Install this skill

npx skills add vercel-labs/agent-skills

Works across Claude Code, Cursor, Codex, Copilot & Antigravity

Finding the extrema in an array is a linear time operation that sorting unnecessarily complicates. When you sort a collection to retrieve the first or last item, you perform O(n log n) work. Iterating through the array once instead reduces this to O(n). This approach avoids memory-heavy operations like creating sorted copies of arrays. It is particularly critical when handling large datasets where sorting overhead causes latency or potential stack overflows. By comparing elements against tracked current min/max values during a single pass, you keep memory allocations low and CPU cycles minimal. This strategy is standard practice for optimizing hot code paths where latency sensitivity is prioritized over brevity. Replace sorting patterns with simple loops to ensure your JavaScript applications remain responsive regardless of the input data size.

When to Use This Skill

  • Finding the most recent timestamp in a list of log entries
  • Identifying price boundaries in a large dataset of products
  • Calculating the oldest and newest items in a transaction history
  • Processing telemetry data to find peak and trough values

How to Invoke This Skill

Example prompts that trigger this skill in Claude Code, Cursor, or Antigravity:

  • Optimize my code for finding the max value
  • Refactor this sort function for better performance
  • Why is my array sorting slow?
  • How to get min and max without sorting
  • Replace array sort for finding extreme values

What this skill does

  • Reduces time complexity from O(n log n) to O(n)
  • Eliminates unnecessary memory allocation from array copying
  • Prevents performance bottlenecks during large data processing
  • Enables simultaneous extraction of both min and max values
  • Ensures stable execution time regardless of array size

When not to use it

  • When the array is already sorted and needs no further processing
  • When you need to perform multiple distinct operations that require an ordered collection anyway

Example workflow

  1. Identify a bottleneck caused by array sorting
  2. Verify the array contains at least one item
  3. Initialize local variables to store the current min and max
  4. Perform a single loop across the array to compare elements
  5. Update variables only when a new value satisfies the condition
  6. Return the collected results after the loop finishes

Pitfalls & limitations

  • !Failing to handle empty arrays which leads to undefined or null pointer errors
  • !Miscalculating the logic when dealing with mixed types or null values
  • !Over-reliance on Math.min/max spread syntax which can cause call stack overflows on massive arrays

FAQ

Why is sorting considered wasteful for min/max?
Sorting requires reordering the entire dataset, whereas finding a min or max only requires knowing the relative value of each element compared to the current best candidate.
Is Math.min faster than a loop?
Math.min is concise for small arrays, but it uses the spread operator which pushes arguments onto the stack, potentially crashing on very large datasets.
Can I use this for non-numeric values?
Yes, as long as you have a stable way to compare values, such as comparing timestamp integers or alphabetical strings.

How it compares

While sorting provides a complete ordered list, this skill focuses strictly on extracting extrema, which reduces computational overhead by eliminating redundant data permutations.

Source & trust

28k stars🕒 Updated 2026-06-10
📄 Full skill instructions — original source: vercel-labs/agent-skills
## Use Loop for Min/Max Instead of Sort

Finding the smallest or largest element only requires a single pass through the array. Sorting is wasteful and slower.

**Incorrect (O(n log n) - sort to find latest):**

interface Project {
id: string
name: string
updatedAt: number
}

function getLatestProject(projects: Project[]) {
const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt)
return sorted[0]
}


Sorts the entire array just to find the maximum value.

**Incorrect (O(n log n) - sort for oldest and newest):**

function getOldestAndNewest(projects: Project[]) {
const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt)
return { oldest: sorted[0], newest: sorted[sorted.length - 1] }
}


Still sorts unnecessarily when only min/max are needed.

**Correct (O(n) - single loop):**

function getLatestProject(projects: Project[]) {
if (projects.length === 0) return null

let latest = projects[0]

for (let i = 1; i < projects.length; i++) {
if (projects[i].updatedAt > latest.updatedAt) {
latest = projects[i]
}
}

return latest
}

function getOldestAndNewest(projects: Project[]) {
if (projects.length === 0) return { oldest: null, newest: null }

let oldest = projects[0]
let newest = projects[0]

for (let i = 1; i < projects.length; i++) {
if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i]
if (projects[i].updatedAt > newest.updatedAt) newest = projects[i]
}

return { oldest, newest }
}


Single pass through the array, no copying, no sorting.

**Alternative (Math.min/Math.max for small arrays):**

const numbers = [5, 2, 8, 1, 9]
const min = Math.min(...numbers)
const max = Math.max(...numbers)


This works for small arrays but can be slower for very large arrays due to spread operator limitations. Use the loop approach for reliability.

How to Use This Skill Unit

Option A: Project-Specific (Recommended)

  1. Click "Download" above
  2. In your project, create the directory: .agent/skills/js-min-max-loop/
  3. Save the file as SKILL.md
  4. The agent will automatically discover the skill based on its description.

Option B: Global Installation (All Agents)

Save the file to these locations to make it available across all projects:

  • Claude Code: ~/.claude/skills/vercel-labs/agent-skills/js-min-max-loop/SKILL.md
  • Cursor: ~/.cursor/skills/vercel-labs/agent-skills/js-min-max-loop/SKILL.md
  • Antigravity: ~/.gemini/antigravity/skills/vercel-labs/agent-skills/js-min-max-loop/SKILL.md

🚀 Install with CLI:
npx skills add vercel-labs/agent-skills

Read the Master Guide: Mastering Agent Skills

Recommended Rules

View more rules

Recommended Workflows

View more workflows

Recommended MCP Servers

View more MCP servers

Take It Further

Maximize your productivity with these powerful resources

📋

Define Your Standards

Set up coding standards to ensure this workflow produces consistent, high-quality results.

Browse Rules Library
📖

Master Workflows

Learn how to create custom workflows, use Turbo Mode, and build your automation library.

Complete Guide

How to use this Skill in Claude Code & Cursor

For Claude Code (CLI)

To use this skill in Claude Code, copy the rule content into your project's custom instructions or follow our Add-Skill CLI guide. This ensures Claude follows your standards during every code generation.

For Cursor & Windsurf

For Cursor or Windsurf, individual skills are best used in the "Rules for AI" section. This specific unit helps the agent avoid javascript performance issues, leading to cleaner, more efficient code.

Why the skill format matters: the standardized Agent Skills format lets your AI agent load detailed instructions only when they are relevant, keeping your prompt clean while improving results.

Source & attribution

This skill is categorized under JavaScript Performance and is published by Vercel Engineering, maintained in vercel-labs/agent-skills.

← Browse All Agent Skills
Sponsored AI assistant. Recommendations may be paid.