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
| Task | Python | JavaScript | Java |
|---|---|---|---|
| By one field | sorted(xs, key=lambda x: x["age"]) | xs.sort((a, b) => a.age - b.age) | xs.sort(Comparator.comparing(P::age)) |
| Descending | reverse=True | (a, b) => b.age - a.age | .reversed() |
| Then by another field | key=lambda x: (x["age"], x["name"]) | a.age - b.age || a.name.localeCompare(b.name) | .thenComparing(P::name) |
| Strings | key=str.casefold | a.name.localeCompare(b.name) | Comparator.comparing(P::name, String.CASE_INSENSITIVE_ORDER) |
| Without mutating | sorted(xs, ...) | xs.toSorted(...) | xs.stream().sorted(...).toList() |
How do I sort a list of dictionaries by a value in 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 itemgetterby_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:
list.sort()returnsNone.people = people.sort(key=...)replaces your list withNone. Use eitherpeople.sort(...)on its own line, orpeople = sorted(people, ...).- Mixed directions. "Age descending, then name ascending" cannot be expressed with one
reverseflag. 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.
people.sort(key=lambda p: p["name"]) # secondarypeople.sort(key=lambda p: p["age"], reverse=True) # primaryHow do I sort a dictionary by value?
Dictionaries keep insertion order, so you sort the items and build a new dictionary:
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?
const people = [ { name: "Ada", age: 36 }, { name: "Linus", age: 28 }, { name: "Grace", age: 36 },];
people.sort((a, b) => a.age - b.age); // ascending by agepeople.sort((a, b) => b.age - a.age); // descendingpeople.sort((a, b) => a.name.localeCompare(b.name)); // by namepeople.sort((a, b) => a.age - b.age || a.name.localeCompare(b.name)); // age, then nameThe 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?
[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?
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#?
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 placeLINQ'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:
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.