1. Home
  2. Blog
  3. Software Development

Software Development

JavaScript Sort Array: Numbers, Objects, Strings and Why 10 Comes Before 5

To sort an array of numbers in JavaScript, pass a compare function: arr.sort((a, b) => a – b). Without it, sort() compares items as text, which is why 10 lands before 5. This guide shows the right way to sort numbers, objects, strings, dates and file names, with output we ran on Node 24.

10 min read
JavaScript sort array explained

Key takeaways

  • The default JavaScript sort array behaviour compares strings: [10, 1, 5, 100, 25].sort() gave [1, 10, 100, 25, 5].
  • Use (a, b) => a - b for ascending numbers and b - a for descending.
  • sort() changes the original array; toSorted() returns a sorted copy and leaves it alone.
  • A compare function that returns a > b (a boolean) is a real bug: it left [3, 1, 2, 5, 4] unsorted in our test.

Sorting looks like the simplest thing an array can do, yet JavaScript’s sort() surprises almost every developer once. Numbers come out in the wrong order, the original array changes behind your back, and names with capitals or accents land in odd places. This JavaScript sort array guide fixes all three. Every example below was run on Node.js v24.22.1, and the outputs are copied from that run. The behaviour is defined by the language standard, so modern browsers match it. If arrays are new to you, start with our JavaScript tutorial for beginners.

Quick answer

const nums = [10, 1, 5, 100, 25];
nums.sort((a, b) => a - b);   // [1, 5, 10, 25, 100]
nums.sort((a, b) => b - a);   // [100, 25, 10, 5, 1]

That one compare function fixes the most common sorting bug. The rest of this guide explains why it works and how to handle every other kind of data.

Why 10 comes before 5

console.log([10, 1, 5, 100, 25].sort());
[ 1, 10, 100, 25, 5 ]

Without a compare function, sort() converts every element to a string and compares them character by character. “10” starts with “1”, which comes before “5”, so 10 sorts before 5, just as “apple” comes before “banana”. This default made sense for the arrays of strings early JavaScript dealt with, and it cannot change without breaking old websites. The fix is to tell sort() how to compare.

How compare functions work

A compare function receives two items, a and b, and returns a number:

Return value Meaning
Negative a comes before b
Positive a comes after b
Zero Keep their current relative order

Subtraction gives exactly this for numbers: if a is smaller, a - b is negative and a goes first. Swap the operands for descending order. Any rule that returns a negative, positive or zero number works, which is how you sort objects, dates and custom orders.

sort() changes the original; toSorted() does not

const orig = [3, 1, 2];
const r = orig.sort();
console.log(orig, r === orig);    // [ 1, 2, 3 ] true

const o2 = [3, 1, 2];
const s2 = o2.toSorted();
console.log(o2, s2);              // [ 3, 1, 2 ] [ 1, 2, 3 ]

sort() sorts in place and returns the same array, so any other variable pointing to that array sees the change. This causes subtle bugs in React state and shared data. toSorted(), added in ES2023, returns a new sorted array and leaves the original untouched. It works in Node 20+ and current browsers. On older platforms, copy first with [...arr].sort(...); see our spread operator guide.

Sorting strings properly

console.log(["banana", "Cherry", "apple"].sort());
console.log(["banana", "Cherry", "apple"].sort((a, b) => a.localeCompare(b)));
console.log(["é", "e", "z", "a"].sort());
console.log(["é", "e", "z", "a"].sort((a, b) => a.localeCompare(b)));
[ 'Cherry', 'apple', 'banana' ]
[ 'apple', 'banana', 'Cherry' ]
[ 'a', 'e', 'z', 'é' ]
[ 'a', 'e', 'é', 'z' ]

The default sort uses UTF-16 code units, so every capital letter comes before every lowercase letter, and accented letters land after “z”. localeCompare() sorts the way people expect, ignoring case differences in order and placing “é” next to “e”. For large lists, create one Intl.Collator and reuse its compare method, which avoids repeated setup.

Natural sort for file names and versions

const files = ["file10", "file2", "file1"];
console.log(files.sort());
console.log(files.sort((a, b) => a.localeCompare(b, undefined, { numeric: true })));
[ 'file1', 'file10', 'file2' ]
[ 'file1', 'file2', 'file10' ]

The numeric: true option compares digit runs as numbers, which gives “natural” order for file names, invoice IDs and simple version labels. It is one of the most useful and least known options in JavaScript.

Sorting an array of objects

const users = [
  { name: "Asha", age: 31, city: "Pune" },
  { name: "Ravi", age: 25, city: "Delhi" },
  { name: "Li",   age: 31, city: "Delhi" },
  { name: "Sam",  age: 25, city: "Pune" },
];
console.log(users.toSorted((a, b) => a.age - b.age).map(u => u.name));
[ 'Ravi', 'Sam', 'Asha', 'Li' ]

Pick the property inside the compare function. Numbers use subtraction; strings use localeCompare. Ravi and Sam are both 25 and kept their original order, which brings us to multi-field sorting and stability. For more on transforming results, see our JavaScript array methods guide.

Sort by several fields

users.toSorted((a, b) => b.age - a.age || a.name.localeCompare(b.name))
[ 'Asha', 'Li', 'Ravi', 'Sam' ]

The || operator is the trick: if the first comparison returns 0 (a tie), JavaScript evaluates the second one. Chain as many fields as you need: byCity || byAge || byName. This sorted by age descending, then by name alphabetically within each age.

Sorting dates

const dates = ["2026-03-01", "2025-12-31", "2026-01-15"].map(d => new Date(d));
console.log(dates.toSorted((a, b) => a - b).map(d => d.toISOString().slice(0, 10)));
[ '2025-12-31', '2026-01-15', '2026-03-01' ]

Subtracting two Date objects gives the difference in milliseconds, so the numeric pattern works directly. Dates stored as ISO strings like “2026-01-15” also sort correctly with plain string comparison, because the format puts the year first. Dates in “15/01/2026” style do not; convert them first.

undefined, NaN and mixed types

console.log([3, undefined, 1, , 2].sort((a, b) => a - b));
console.log([3, NaN, 1, 2].sort((a, b) => a - b));
console.log([10, "9", 8, "1"].sort());
console.log([10, "9", 8, "1"].sort((a, b) => a - b));
[ 1, 2, 3, undefined, <1 empty item> ]
[ 3, NaN, 1, 2 ]
[ '1', 10, 8, '9' ]
[ '1', 8, '9', 10 ]

undefined values and empty slots always move to the end and are never passed to your compare function. NaN is worse: a - NaN is NaN, which the sort treats like 0, and in our run the whole array stayed unsorted. Clean or filter your data before sorting. Mixed strings and numbers sort correctly with subtraction because - converts strings to numbers, but the safer fix is converting the data once with .map(Number).

The boolean compare bug

console.log([3, 1, 2, 5, 4].sort((a, b) => a > b));
[ 3, 1, 2, 5, 4 ]

Older tutorials sometimes show (a, b) => a > b. It returns true or false, which convert to 1 or 0, never a negative number. The sort never learns that one item should come first, and in our run nothing moved at all. Some engines happen to give a sorted result on small arrays, which is why this bug survives reviews. Always return a number.

Tip: if a compare function contains > or <, it must return -1, 1 or 0 explicitly, for example a > b ? 1 : a < b ? -1 : 0. For numbers, plain subtraction is simpler.

Is JavaScript sort stable?

Yes, since ES2019 the standard requires a stable sort: items that compare equal keep their original order. We sorted ten items by an even or odd group and got 0,2,4,6,8,1,3,5,7,9, with each group still in its original order. Stability lets you sort by a secondary field first and the primary field second, the same technique our Python sort list guide uses.

How fast is sorting?

We sorted one million random integers on Node 24:

Method Time Correct numeric order?
[...big].sort((a, b) => a - b) 274 ms Yes
new Int32Array(big).sort() 75 ms Yes
[...big].sort() (default) 314 ms No, string order

Typed arrays such as Int32Array and Float64Array sort numerically by default and were about 3.6 times faster here, a useful trick for large numeric data. The broken default sort was also the slowest, because it converts every number to a string first.

Common mistakes

  • No compare function for numbers. Always pass (a, b) => a - b.
  • Mutating shared data. Use toSorted() or copy first.
  • Returning a boolean. Return a number.
  • Sorting text with > and <. Use localeCompare for human-friendly order.
  • Sorting dirty data. Remove NaN and convert strings to numbers before sorting.

JavaScript sort array cheat sheet

Goal Code
Numbers ascending arr.sort((a, b) => a - b)
Numbers descending arr.sort((a, b) => b - a)
Without mutating arr.toSorted(fn)
Strings, human order arr.sort((a, b) => a.localeCompare(b))
Natural order localeCompare(b, undefined, {numeric: true})
Objects by field arr.sort((a, b) => a.age - b.age)
Several fields (a, b) => a.x - b.x || a.y.localeCompare(b.y)
Dates arr.sort((a, b) => a - b)
Reverse a sorted array arr.toReversed()

Final thoughts

JavaScript sort array problems almost always trace back to three defaults: items compare as strings, the original array is changed, and a compare function must return a number. Pass a numeric compare function, prefer toSorted() for shared data, use localeCompare for text, and clean your data first. Then sorting becomes as boring and reliable as it should be. For keyed data, our Map vs Object guide is a good next read.

Frequently asked questions

Why does JavaScript sort numbers incorrectly?

Without a compare function, sort converts numbers to strings and compares them as text, so 10 comes before 5. Pass (a, b) => a – b to sort numerically.

How do I sort an array of objects by a property in JavaScript?

Compare the property inside the function: arr.sort((a, b) => a.age – b.age) for numbers, or a.name.localeCompare(b.name) for strings.

Does sort() change the original array?

Yes. sort works in place and returns the same array. Use toSorted() or sort a copy made with the spread operator to keep the original unchanged.

How do I sort in descending order in JavaScript?

Reverse the subtraction: arr.sort((a, b) => b – a) for numbers, or b.localeCompare(a) for strings.

Is Array.prototype.sort stable?

Yes. Since ES2019 the specification requires a stable sort, so equal items keep their original relative order in all modern engines.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
Software Development

HTTP Methods Explained: GET, POST, PUT, PATCH, DELETE, Tested on a Live Server

HTTP methods explained with a small server we ran: GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS, safe vs idempotent,…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Databases & SQL

SQL ORDER BY Multiple Columns: ASC, DESC, NULLS LAST, Case and Custom Order

SQL ORDER BY with multiple columns explained with tested queries: mixed ASC and DESC, tie-breakers, NULLS FIRST and LAST, case-insensitive…

Read article →
Databases & SQL

SQL Running Total: SUM OVER, Per-Group Totals, Moving Sums and the RANGE Trap

How to calculate a SQL running total with SUM() OVER: per-group totals, daily cumulative sums, moving sums, percent of total,…

Read article →
Software Development

JavaScript Sort Array: Numbers, Objects, Strings and Why 10 Comes Before 5

How to sort an array in JavaScript correctly: numbers with a compare function, objects by one or more fields, strings…

Read article →
Software Development

Python String Methods: Cheat Sheet, Real Examples and the strip() Trap

Python string methods with tested examples: split, join, strip, replace, find, startswith, is-methods, casefold, partition and translate, plus the strip()…

Read article →
Software Development

Python zip() Explained: Loop Two Lists at Once, Unzip, strict=True and Traps

Python zip() pairs items from several lists in one loop. Tested examples for dicts, unzipping with *, strict=True, zip_longest, sliding…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
Software Development

UTF-8 Encoding Explained: How Text Becomes Bytes and How to Fix Garbled Text

UTF-8 encoding explained with byte-level examples we ran in Python: how characters become 1 to 4 bytes, why café turns…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →
Software Testing

Retesting vs Regression Testing: 8 Key Differences with a Real Bug Fix Example

Retesting vs regression testing explained with a real bug fix run in pytest: retesting confirmed the fix, the regression run…

Read article →
Databases & SQL

Delete Duplicate Rows in SQL: 5 Safe Methods, Tested Step by Step

How to delete duplicate rows in SQL safely: find them, preview them, then remove them with ROW_NUMBER, MIN(id), EXISTS, rowid…

Read article →
Databases & SQL

SQL RANK vs DENSE_RANK vs ROW_NUMBER: Differences with Tested Examples

SQL RANK vs DENSE_RANK vs ROW_NUMBER in one table: how each handles ties, top-N per group, the second-highest salary trap…

Read article →
Software Development

JavaScript Optional Chaining (?.) Explained: 8 Examples, ?? Defaults and Traps

JavaScript optional chaining stops “Cannot read properties of undefined” errors. 8 tested examples for properties, arrays and methods, ?? vs…

Read article →
Artificial Intelligence

RAG Chunking Strategies Explained: Fixed, Overlap, Sentence, Recursive and Headings, Measured

RAG chunking strategies compared on one document with tiktoken 0.14: fixed-size, overlap, sentence packing, recursive splitting and heading-based chunks, measuring…

Read article →
DevOps

Git Stash Explained: Save, Apply, Pop and Untracked Files, Tested

Git stash explained with commands we ran on Git 2.56: push with a message, untracked files, list and show, apply…

Read article →
Software Testing

Pairwise Testing Explained: How All-Pairs Cuts 216 Tests to 13, Tested

Pairwise testing explained with a generator we ran in Python 3.13: a checkout with 216 combinations covered by 13 tests,…

Read article →
Test Automation

Test Doubles Explained: Dummy, Stub, Spy, Mock and Fake, with Tested Python Code

Test doubles explained with one Python example run in pytest 9.2: dummy, stub, spy, mock and fake, when to use…

Read article →
Databases & SQL

SQL COALESCE Explained: Defaults, NULLIF, IFNULL vs ISNULL and Traps, Tested

SQL COALESCE explained with queries we ran in SQLite 3.50: first non-null values, empty strings, NULL in maths, NULLIF for…

Read article →
Databases & SQL

SQL Self Join Explained: Employee-Manager, Pairs and Row Comparisons, Tested

SQL self join explained with queries we ran in SQLite 3.50: employee and manager, earning more than the manager, unique…

Read article →
Artificial Intelligence

LLM Context Window Explained: Tokens, Limits and How to Fit More, Measured

The LLM context window explained with token counts we measured using tiktoken: words vs tokens for prose, code and Hindi,…

Read article →
DevOps

Git Cherry-Pick Explained: Copy the Commit You Need, Safely, Tested

Git cherry-pick explained with commands we ran in Git 2.56: copying a hotfix to a release branch, new hashes and…

Read article →
Test Automation

Snapshot Testing Explained: How It Works, When It Helps and When It Hurts

Snapshot testing explained with a pytest and syrupy demo we ran: creating snapshots, reading the diff after a code change,…

Read article →
Software Testing

Mutation Testing Explained: Why 100% Coverage Still Missed Our Bug

Mutation testing explained with a small mutation tool we built and ran: 14 mutants, a test suite with 100% line…

Read article →
Artificial Intelligence

Prompt Injection Explained: How AI Apps Get Tricked and How to Defend Them

Prompt injection explained for builders: direct and indirect attacks, why keyword filters fail (our test blocked 1 of 4), and…

Read article →
DevOps

DNS Records Explained: A, AAAA, CNAME, MX, TXT and TTL With Real Lookups

DNS records explained with lookups we ran: how resolution works, A and AAAA, CNAME rules, MX and null MX, TXT…

Read article →
DevOps

Feature Flags Explained: Safe Releases, Gradual Rollouts and Flag Hygiene

Feature flags explained with a rollout simulation we ran: flag types, percentage rollouts with stable hashing, kill switches, allow lists,…

Read article →
Test Automation

Test Data Generation With Python Faker: Realistic, Repeatable and Safe Data

Test data generation with Python Faker, run and measured: seeding for repeatable data, locales, unique values, domain-shaped records, edge cases…

Read article →
Software Testing

Shift-Left Testing Explained: Find Bugs Earlier Without Slowing the Team

Shift-left testing explained: what it means, why early defects are cheaper, practices from requirement reviews to CI checks, the tester's…

Read article →
Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →