Key points
- Without a compare function, sort() treats everything as text, and it mutates the original array: use toSorted() or a copy.
- For numbers and dates compare numeric values; for strings, Intl.Collator handles accents, case and embedded numbers.
- A small comparator factory covers real-world needs: multiple criteria, empty values last, ascending or descending.
Sorting a list looks like the easiest thing in JavaScript, until amounts come out as 1, 10, 100, 9, “Émilie” lands after “Zoe”, or an array that was supposed to stay untouched turns up sorted somewhere else in the app. Those three problems come up again and again, in order lists, dashboards and product catalogues. Here’s how to sort an array of objects correctly by number, by date and by string, and how to chain several criteria cleanly with two small helpers you can reuse in every project.
Why sort() catches you out
By default, Array.prototype.sort() converts every element to a string and compares those strings character by character. For numbers, that means the result is wrong as soon as they don’t all have the same number of digits. The fix is to always pass a compare function, which receives two elements and returns a negative number if the first should come first, a positive number if it should come after, and zero if they’re equivalent:
[10, 9, 1, 100].sort(); // [1, 10, 100, 9] ← compared as text
[10, 9, 1, 100].sort((a, b) => a - b); // [1, 9, 10, 100]
[10, 9, 1, 100].sort((a, b) => b - a); // [100, 10, 9, 1]
const prices = [30, 5, 12];
const sorted = prices.sort((a, b) => a - b);
console.log(prices === sorted); // true: sort() changes the original array
const copy = prices.toSorted((a, b) => a - b); // new array, the original is untouched
const copy2 = [...prices].sort((a, b) => a - b); // same thing for older browsers
The second trap is less obvious: sort() sorts in place and returns the same array. If that array lives in shared state (a store, a component’s props, cached data), you’ve just changed it for everyone. On one of our projects, a sort applied inside a display component changed the order of a list that a CSV export used elsewhere in the app: the kind of bug that takes a long time to trace back to its cause.
toSorted() returns a new sorted array and leaves the original alone. It’s available in current browsers and in Node.js from version 20. If you need to support older browsers, copying with [...array] before calling sort() does exactly the same job.
Sorting by number and by date
With an array of objects, the compare function just reads the relevant property. For amounts, subtraction is enough. For dates, compare numeric timestamps, not free-form strings:
const orders = [
{ ref: 'A-12', date: '2026-11-03T10:15:00Z', total: 89.9 },
{ ref: 'A-15', date: '2026-11-28T08:02:00Z', total: 12 },
{ ref: 'A-09', date: '2026-10-17T16:40:00Z', total: 240 },
];
// Generic comparator: returns -1, 0 or 1, never NaN
const cmp = (x, y) => (x > y) - (x < y);
// By amount, highest first
orders.toSorted((a, b) => b.total - a.total);
// By date, newest first
orders.toSorted((a, b) => Date.parse(b.date) - Date.parse(a.date));
// Robust version: missing or invalid date → pushed to the end
const timestamp = (d) => {
const t = Date.parse(d ?? '');
return Number.isNaN(t) ? -Infinity : t;
};
orders.toSorted((a, b) => cmp(timestamp(b.date), timestamp(a.date)));
A few notes from practice. Subtracting a - b is fine as long as both values are valid numbers; as soon as one is undefined or a date is invalid, the result is NaN, and a comparator that returns NaN produces an inconsistent order without any error in the console. The small cmp comparator above always returns -1, 0 or 1, which avoids the issue and also works for plain strings.
Full ISO 8601 dates (2026-11-03T10:15:00Z) actually sort correctly as text too, provided they all share exactly the same format and offset. As soon as formats get mixed (11/03/2026, dates without times, different UTC offsets), go through Date.parse(), or better, have your API return consistent ISO dates. And be wary of Date.parse('11/03/2026'): how that format is read isn’t guaranteed and depends on the JavaScript engine.
Sorting strings properly: accents, case and numbers
Strings raise a different problem. The default comparison uses character codes, so capitals come before lowercase letters and accented letters come after “z”. For customer names, cities or anything multilingual, that’s not acceptable. The answer is Intl.Collator, which applies a language’s sorting rules:
const names = ['Zoé', 'andré', 'Émilie', 'eric'];
names.toSorted();
// ['Zoé', 'andré', 'eric', 'Émilie'] : capitals first, accented letters last
const collator = new Intl.Collator('en', { sensitivity: 'base', numeric: true });
names.toSorted(collator.compare);
// ['andré', 'Émilie', 'eric', 'Zoé']
['Batch 10', 'Batch 2', 'Batch 1'].toSorted(collator.compare);
// ['Batch 1', 'Batch 2', 'Batch 10'] thanks to numeric: true
// On an array of objects
customers.sort((a, b) => collator.compare(a.name, b.name));
The two options you’ll use most:
sensitivity: 'base': “e”, “E” and “é” are treated as equal for sorting, which is what a reader expects.numeric: true: runs of digits are compared as numbers, so “Batch 2” comes before “Batch 10”. Essential for references, room numbers or file names.
a.localeCompare(b, 'en', options) gives the same result, but it rebuilds the comparison rules internally on every call. On a few dozen items you won’t notice; on several thousand rows, creating one Intl.Collator and reusing its compare method is noticeably faster. It’s become our default for every data table in the applications we build.
Multiple criteria, empty values and sort direction
Real applications rarely sort on a single key: urgent tickets first, then by due date, then by customer. And there’s always incomplete data, a missing due date, a customer with no name. Rather than writing a fifteen-line comparator each time, we use two small helpers:
// Comparator factory: value to compare, compare function, direction
function by(getter, compare = cmp, dir = 1) {
return (a, b) => {
const x = getter(a), y = getter(b);
const vx = x == null || x === '', vy = y == null || y === '';
if (vx || vy) return vx - vy; // empty values always last
return dir * compare(x, y);
};
}
// Combine criteria: the next one only applies on a tie
const thenBy = (...comparators) => (a, b) => {
for (const c of comparators) {
const r = c(a, b);
if (r !== 0) return r;
}
return 0;
};
const statusOrder = { urgent: 0, open: 1, closed: 2 };
tickets.sort(thenBy(
by(t => statusOrder[t.status]), // urgent first
by(t => Date.parse(t.dueDate), cmp), // then nearest due date
by(t => t.client, new Intl.Collator('en').compare) // then customer, alphabetical
));
by() extracts the value to compare, picks the compare function and the direction (1 for ascending, -1 for descending), and always puts empty values last, whichever direction you choose. That’s nearly always what users want: sorting by due date descending shouldn’t push every ticket without a due date to the top. thenBy() chains criteria: the second only applies when the first is a tie, and so on.
FAQ
Why does my sort give a different order in different browsers?
Almost always because the compare function is inconsistent: it returns a boolean (a > b) instead of a number, or NaN because of a missing value. Each engine then runs its algorithm on contradictory answers. Always return a negative number, a positive number or zero.
How do I ignore accents but keep upper and lower case distinct?
Use sensitivity: 'case' in Intl.Collator: accents are ignored, case is not. 'accent' does the opposite, and 'variant' (the default for sorting) distinguishes everything.
Your dashboards and business lists deserve to be fast and correct. We design clear, accessible data interfaces built for the real volumes our clients work with.



