Skip to content
jshacks.dev
Fundamentals

How to Sort an Array of Objects by a Property

Sort an array of objects by a property in JavaScript with sort and toSorted, handle strings, numbers, missing values and several keys, and avoid mutation.

10 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, Node.js and npm logos.

To sort an array of objects by a property in JavaScript, pass a comparator to sort or toSorted that returns a negative number, zero or a positive number for two items, for example (a, b) => a.age - b.age. That one line covers numbers. Strings need localeCompare, missing values need a rule of their own, and sorting by two keys needs a comparator that falls through to the second key when the first ties. The other trap is mutation: sort rearranges the array you call it on, while toSorted returns a new array. This post builds up from the one-liner to a small reusable helper, and shows the output of every step on Node.js 24, where toSorted is available (it shipped in ES2023 and Node.js 20).

The basic comparator

A comparator receives two items, a and b, and answers one question: should a come before b? A negative result means yes, a positive result means no, and zero means they are equal for sorting purposes. The method then arranges the whole array from many such answers.

JavaScript
const users = [
  { name: "Mia", age: 31, team: "web" },
  { name: "Omar", age: 25, team: "api" },
  { name: "Lena", age: 31, team: "api" },
  { name: "Ivo", age: 19, team: "web" },
];

const show = (list) => list.map((u) => `${u.name}:${u.age}`).join(" ");

console.log(show(users.toSorted((a, b) => a.age - b.age)));
console.log(show(users.toSorted((a, b) => b.age - a.age)));
console.log(show(users));
Text
Ivo:19 Omar:25 Mia:31 Lena:31
Mia:31 Lena:31 Omar:25 Ivo:19
Mia:31 Omar:25 Lena:31 Ivo:19

Subtracting the numbers gives a negative result when a.age is smaller, so smaller ages come first. Swapping the operands reverses the order. The third line shows that toSorted left the original array alone. Mia and Lena are both 31, and they keep their original relative order in both results, because sort has been stable since ES2019: items that compare equal are never swapped.

Why the default sort is wrong for objects

Called without a comparator, sort converts every item to a string and compares the strings. For objects that string is [object Object] for all of them, so nothing is reordered in a useful way, and for numbers the string comparison puts 10 before 9.

JavaScript
console.log([10, 9, 1].sort());
console.log(["10", "9", "1"].sort());
console.log([10, 9, 1].sort((a, b) => a - b));
Text
[ 1, 10, 9 ]
[ '1', '10', '9' ]
[ 1, 9, 10 ]

Always pass a comparator when the items are anything but plain strings you want in code-unit order.

Sorting strings

Subtracting does not work for strings, since "a" - "b" is NaN. Use localeCompare, which returns a negative number, zero or a positive number and follows the language rules of the runtime.

JavaScript
const byName = users.toSorted((a, b) => a.name.localeCompare(b.name));
console.log(byName.map((u) => u.name).join(" "));

const words = [{ w: "zebra" }, { w: "Äpfel" }, { w: "apple" }, { w: "Zoo" }];
console.log(words.toSorted((a, b) => a.w.localeCompare(b.w, "de")).map((x) => x.w).join(" "));
console.log(words.toSorted((a, b) => (a.w < b.w ? -1 : a.w > b.w ? 1 : 0)).map((x) => x.w).join(" "));
Text
Ivo Lena Mia Omar
apple Äpfel zebra Zoo
Zoo apple zebra Äpfel

The second line uses German rules, in which Ä sorts next to A, and letter case does not push Zoo to the front. The third line uses the plain < operator, which compares UTF-16 code units: every capital letter comes before every lowercase letter, and Ä lands at the very end. That is correct for identifiers and wrong for names shown to people. The full story of accents, case and numbers inside strings is in the next post on sorting strings correctly.

Sorting by more than one key

When the first key ties, the comparator should move on to the second. Because a tie is zero, which is falsy, the || operator does this in one expression.

JavaScript
const ranked = users.toSorted(
  (a, b) => b.age - a.age || a.name.localeCompare(b.name)
);
console.log(show(ranked));

const grouped = users.toSorted(
  (a, b) => a.team.localeCompare(b.team) || a.age - b.age
);
console.log(grouped.map((u) => `${u.team}/${u.name}`).join(" "));
Text
Lena:31 Mia:31 Omar:25 Ivo:19
api/Omar api/Lena web/Ivo web/Mia

The first result sorts by age, oldest first, and breaks the tie between Lena and Mia alphabetically. The second sorts by team, then by age within each team. The || trick works because the first comparison returns 0 exactly when the keys are equal. It would be a bug with a comparator that returns NaN or undefined for ties, so keep every comparison to a number.

Missing and null values

Real data has gaps. A subtraction involving undefined gives NaN, and the specification treats a NaN result from a comparator as 0, which breaks the consistency a sort relies on and gives an order that depends on the engine. Decide where gaps go and write that rule down in the comparator.

JavaScript
function compareNullsLast(a, b) {
  if (a == null && b == null) return 0;
  if (a == null) return 1;
  if (b == null) return -1;
  return a < b ? -1 : a > b ? 1 : 0;
}

const results = [
  { id: 1, score: 7 },
  { id: 2, score: null },
  { id: 3, score: 3 },
  { id: 4 },
];

const sorted = results.toSorted((a, b) => compareNullsLast(a.score, b.score));
console.log(sorted.map((r) => r.id).join(" "));
Text
3 1 2 4

Scores 3 and 7 come first in ascending order, then the two records without a score in their original order, because the comparator says they tie. To put gaps first, swap the 1 and -1. To sort descending with gaps still last, reverse only the final line, not the null handling.

A reusable helper

The same comparator keeps being rewritten, so a small function that builds one is worth having. It takes a key, or a function that reads a key, and a direction.

JavaScript
function by(key, direction = "asc") {
  const read = typeof key === "function" ? key : (item) => item[key];
  const sign = direction === "desc" ? -1 : 1;

  return (a, b) => {
    const x = read(a);
    const y = read(b);
    if (x == null && y == null) return 0;
    if (x == null) return 1;
    if (y == null) return -1;
    if (typeof x === "string" && typeof y === "string") {
      return sign * x.localeCompare(y);
    }
    return sign * (x < y ? -1 : x > y ? 1 : 0);
  };
}

const thenBy = (...comparators) => (a, b) => {
  for (const compare of comparators) {
    const result = compare(a, b);
    if (result !== 0) return result;
  }
  return 0;
};

console.log(show(users.toSorted(by("age", "desc"))));
console.log(show(users.toSorted(thenBy(by("team"), by("age", "desc"), by("name")))));
console.log(show(users.toSorted(by((u) => u.name.length))));
Text
Mia:31 Lena:31 Omar:25 Ivo:19
Lena:31 Omar:25 Mia:31 Ivo:19
Ivo:19 Mia:31 Omar:25 Lena:31

The second line sorts by team, then oldest first inside a team, then by name: the api team gives Lena (31) before Omar (25), the web team gives Mia (31) before Ivo (19). The third line sorts by name length, so Ivo and Mia (3 letters) come before Omar and Lena (4 letters), and the stable sort keeps the original order inside each pair. The helper puts gaps last in both directions, because the null checks run before the sign is applied.

sort versus toSorted

sort sorts in place and returns the same array. That is a hazard whenever the array is shared, for example state in a UI framework or an argument the caller still uses.

JavaScript
const original = [{ n: 3 }, { n: 1 }, { n: 2 }];

const copy = original.toSorted((a, b) => a.n - b.n);
console.log(original.map((x) => x.n).join(""), copy.map((x) => x.n).join(""));

const same = original.sort((a, b) => a.n - b.n);
console.log(original.map((x) => x.n).join(""), same === original);

const legacy = [...original].sort((a, b) => b.n - a.n);
console.log(original.map((x) => x.n).join(""), legacy.map((x) => x.n).join(""));
Text
312 123
123 true
123 321

toSorted returned a new array and left original as 312. sort rearranged original and returned the very same array, as same === original confirms. On a runtime without toSorted, copy first with the spread operator and sort the copy. Note that all of these copies are shallow: the objects inside are shared, so changing copy[0].n changes the object in original too.

Dates and mixed types

Dates compare correctly by subtracting, since a Date converts to its millisecond timestamp. ISO 8601 strings in a single format compare correctly as plain strings, because the most significant part comes first.

JavaScript
const events = [
  { title: "Launch", at: "2026-03-01T09:00:00Z" },
  { title: "Kickoff", at: "2026-01-15T09:00:00Z" },
  { title: "Review", at: "2026-02-10T09:00:00Z" },
];

console.log(events.toSorted((a, b) => new Date(a.at) - new Date(b.at)).map((e) => e.title).join(" "));
console.log(events.toSorted((a, b) => a.at.localeCompare(b.at)).map((e) => e.title).join(" "));
Text
Kickoff Review Launch
Kickoff Review Launch

Both give the same order. The string version only works while every value uses the same format and the same offset, so a value such as 2026-03-01T09:00:00+02:00 mixed in with Z values would sort wrongly. When formats vary, parse first.

Choosing an approach

SituationUse
Numbers(a, b) => a.value - b.value
Strings shown to peoplea.name.localeCompare(b.name) with a locale
Two keysChain two comparisons with the `` operator
Values may be missingA comparator with explicit null handling
You must not change the arraytoSorted, or [...array].sort(...)
Sorting a large array by an expensive keyCompute the key once, sort, then discard it

Practical rules we follow

Never call sort without a comparator on anything but strings. Prefer toSorted and fall back to copy-then-sort. Return numbers only, never booleans: a comparator returning a > b yields true or false, which converts to 1 or 0 and never to a negative value, so it is wrong in a way that often looks right on a short list. Write null handling once, in a helper. And add the tie-breaker key even if the data looks unique today, so the order stays the same when it stops being unique.

Where this approach stops

A comparator runs many times per item, about n log n comparisons for n items, so a key that is expensive to read is read over and over. For heavy keys, compute them once into an array of pairs, sort that, and map back. Sorting is also limited to what a comparator can express on two items at a time: a ranking that depends on the whole list, such as sorting by a percentile, needs the statistics computed first. The reference for the algorithm and its guarantees is Array.prototype.toSorted on MDN.

Sorting by an expensive key

A comparator is called many times for each item, roughly n log n calls for n items, and every call reads the key from both sides. When reading the key is cheap, such as a property access, that does not matter. When reading it means parsing a date, lowercasing a long string or running a regular expression, the same work happens again and again for the same item. The fix has a name from older languages, decorate, sort, undecorate: compute the key once per item, pair it with the item, sort the pairs, and keep only the items.

JavaScript
const files = [{ name: "b.TXT" }, { name: "A.txt" }, { name: "c.txt" }];
let reads = 0;

const normalized = (file) => {
  reads++;
  return file.name.toLowerCase();
};

const sortedFiles = files
  .map((file) => ({ file, key: normalized(file) }))
  .sort((x, y) => (x.key < y.key ? -1 : x.key > y.key ? 1 : 0))
  .map(({ file }) => file);

console.log(reads, sortedFiles.map((f) => f.name).join(" "));
Text
3 A.txt b.TXT c.txt

The key function ran three times, once per item, whatever the number of comparisons the engine made. The extra array of pairs costs memory, so this is worth doing when the key is expensive or when the same sorted order is needed repeatedly, and not for a property read. A related habit is to sort once and reuse the result, instead of sorting again inside a render function or a loop that runs on every event.

Testing a comparator

A comparator that returns the wrong sign for some input does not fail loudly. It produces an order that looks plausible on a short list. Three cheap checks catch most mistakes. First, sort a list that is already in order and a list in reverse order, and expect the same result from both. Second, include equal keys and check that their original order survives, since stability is part of what callers rely on. Third, include the awkward values from your real data, such as an empty string, null, a number stored as text and a name that starts with an accent. A comparator that handles those handles the rest. Keep the sample data in a test, so a later change to the comparator, for instance to add a second key, cannot break the first one without a failing test.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.