SoftwareSideHustles
How-To

How to Sort a List of Objects by a Property (Python, JavaScript, Java, C#)

Sort lists of dictionaries, objects and records by one or more fields, ascending or descending, with missing values — and the JavaScript default sort that puts 10 before 9.

By Software Side Hustles Editorial Team · Published · Updated · 5 min read

Quick answer: pass a key or comparator that pulls out the field. Python: sorted(people, key=lambda p: p["age"]). JavaScript: people.sort((a, b) => a.age - b.age). Java: people.sort(Comparator.comparing(Person::age)). C#: people.OrderBy(p => p.Age). For descending order add reverse=True, swap a and b, call .reversed() or use OrderByDescending.

Sorting by a field: cheat sheet

TaskPythonJavaScriptJava
By one fieldsorted(xs, key=lambda x: x["age"])xs.sort((a, b) => a.age - b.age)xs.sort(Comparator.comparing(P::age))
Descendingreverse=True(a, b) => b.age - a.age.reversed()
Then by another fieldkey=lambda x: (x["age"], x["name"])a.age - b.age || a.name.localeCompare(b.name).thenComparing(P::name)
Stringskey=str.casefolda.name.localeCompare(b.name)Comparator.comparing(P::name, String.CASE_INSENSITIVE_ORDER)
Without mutatingsorted(xs, ...)xs.toSorted(...)xs.stream().sorted(...).toList()

How do I sort a list of dictionaries by a value in Python?

python
people = [
{"name": "Ada", "age": 36},
{"name": "Linus", "age": 28},
{"name": "Grace", "age": 36},
]
by_age = sorted(people, key=lambda p: p["age"])
oldest_first = sorted(people, key=lambda p: p["age"], reverse=True)
from operator import itemgetter
by_age_then_name = sorted(people, key=itemgetter("age", "name"))

For objects and dataclasses, use attrgetter("age") or lambda p: p.age.

Two things trip people up:

  1. list.sort() returns None. people = people.sort(key=...) replaces your list with None. Use either people.sort(...) on its own line, or people = sorted(people, ...).
  2. Mixed directions. "Age descending, then name ascending" cannot be expressed with one reverse flag. Negate numeric fields — key=lambda p: (-p["age"], p["name"]) — or sort twice, because Python's sort is stable: sort by the secondary key first, then by the primary key.
python
people.sort(key=lambda p: p["name"]) # secondary
people.sort(key=lambda p: p["age"], reverse=True) # primary

How do I sort a dictionary by value?

Dictionaries keep insertion order, so you sort the items and build a new dictionary:

python
scores = {"ada": 92, "linus": 78, "grace": 95}
dict(sorted(scores.items(), key=lambda kv: kv[1], reverse=True))
# {'grace': 95, 'ada': 92, 'linus': 78}

For the top N only, heapq.nlargest(3, scores.items(), key=lambda kv: kv[1]) avoids sorting everything.

How do I sort an array of objects in JavaScript?

javascript
const people = [
{ name: "Ada", age: 36 },
{ name: "Linus", age: 28 },
{ name: "Grace", age: 36 },
];
people.sort((a, b) => a.age - b.age); // ascending by age
people.sort((a, b) => b.age - a.age); // descending
people.sort((a, b) => a.name.localeCompare(b.name)); // by name
people.sort((a, b) => a.age - b.age || a.name.localeCompare(b.name)); // age, then name

The comparator returns a negative number if a should come first, positive if b should, and zero if they tie. The || trick works because a tie returns 0, which is falsy, so the second comparison decides.

Why does JavaScript sort numbers wrong?

javascript
[10, 9, 1].sort(); // [1, 10, 9]

Without a comparator, sort() converts elements to strings and compares them as text, and "10" comes before "9". Always pass (a, b) => a - b for numbers.

Also note that sort() mutates the array and returns the same array. In React state or shared data that causes bugs; use toSorted() (ES2023) or [...people].sort(...) instead.

How do I sort a List of objects in Java?

java
record Person(String name, int age) {}
List<Person> people = new ArrayList<>(List.of(
new Person("Ada", 36), new Person("Linus", 28), new Person("Grace", 36)));
people.sort(Comparator.comparingInt(Person::age));
people.sort(Comparator.comparingInt(Person::age).reversed());
people.sort(Comparator.comparingInt(Person::age).thenComparing(Person::name));

List.of(...) on its own is immutable — calling sort on it throws UnsupportedOperationException, which is why the example copies it into an ArrayList. For a sorted copy without mutation: people.stream().sorted(comparator).toList().

Avoid the old subtraction comparator (a, b) -> a.age - b.age in Java: with large or negative values the subtraction can overflow and produce the wrong sign. Integer.compare and Comparator.comparingInt do not have that problem.

How do I sort a list by a property in C#?

csharp
var sorted = people.OrderBy(p => p.Age).ThenBy(p => p.Name).ToList();
var desc = people.OrderByDescending(p => p.Age).ToList();
people.Sort((a, b) => a.Age.CompareTo(b.Age)); // in place

LINQ's OrderBy is stable and returns a new sequence; List<T>.Sort sorts in place and is not guaranteed stable.

Sorting with missing values (None, null, undefined)

Real data has gaps. In Python, comparing None with a number raises TypeError: '<' not supported between instances of 'NoneType' and 'int'. Put missing values last with a tuple key:

python
sorted(people, key=lambda p: (p.get("age") is None, p.get("age") or 0))

In Java, wrap the key comparator: Comparator.comparing(Person::age, Comparator.nullsLast(Comparator.naturalOrder())). In JavaScript, decide explicitly — undefined values are always moved to the end by sort, but null is not, and null - 5 is -5, so nulls silently behave like zero.

What does "stable sort" mean and why does it matter?

A stable sort keeps items with equal keys in their original relative order. Python's sorted, JavaScript's Array.prototype.sort (guaranteed since ES2019), Java's List.sort for objects and LINQ's OrderBy are all stable. Stability is what makes the "sort twice" technique work, and it keeps UI lists from shuffling when two rows tie.

Frequently asked questions

How do I sort by multiple fields?

Return a tuple key in Python, chain comparisons with || in JavaScript, use thenComparing in Java, and ThenBy in C#.

How do I sort strings case-insensitively?

Python: key=str.casefold. JavaScript: a.localeCompare(b, undefined, { sensitivity: "base" }). Java: String.CASE_INSENSITIVE_ORDER. For user-facing lists, locale-aware comparison also sorts accented letters sensibly.

How do I sort dates?

Sort by the date value, not its display string — "03/01/2026" sorts before "12/31/2025" as text. ISO 8601 strings (2026-01-03) do sort correctly as text. See working with dates and time zones.

What is the time complexity of sorting?

O(n log n) for the built-in sorts in all these languages (Timsort in Python, for Java objects and in V8, the engine behind Chrome and Node.js). See Big O notation explained.

Where this skill pays off

Our free top-three-scores exercise shows an AI response that forgets JavaScript's default string sort — it works on the example and fails on real data. Reviewing code like that, and explaining the fix clearly, is paid work on AI training platforms. Read how developers earn money training AI models.

Cookies on this site

We use essential cookies to run the questionnaire, practice labs and sign-in. With your permission we'd also like to use analytics to understand which pages help people, and advertising cookies to measure our Google Ads. Rejecting never limits any feature. Cookie policy