Js Sort Array Of Objects By Property

7 min read

Sorting an array of objects is one of the most fundamental tasks in JavaScript development. Whether you are building a dashboard that ranks users by score, an e-commerce product grid sorted by price, or a content management system ordering articles by date, the ability to js sort array of objects by property efficiently is indispensable. The native Array.prototype.sort() method provides the engine for this operation, but its default behavior—converting elements to strings and comparing UTF-16 code units—often leads to unexpected results when dealing with numbers, dates, or nested properties. Mastering the compare function unlocks the full potential of this method, allowing for precise, performant, and predictable ordering of complex data structures.

Understanding the Core Mechanism: The Compare Function

The sort() method accepts an optional compare function (often called a comparator) that defines the sort order. This function takes two arguments, traditionally named a and b, representing two elements being compared. The return value dictates their final positions:

  • Negative value (< 0): a comes before b.
  • Positive value (> 0): b comes before a.
  • Zero (0): Leave a and b unchanged relative to each other (stable sort).

This simple contract is the foundation for all custom sorting logic. Still, without a compare function, [10, 2, 30]. sort() yields [10, 2, 30] because "10" < "2" lexicographically. With a comparator (a, b) => a - b, the result correctly becomes [2, 10, 30].

Sorting by Numeric Properties

Numeric sorting is the most common use case. Imagine an array of product objects:

const products = [
  { id: 1, name: 'Laptop', price: 1200 },
  { id: 2, name: 'Mouse', price: 25 },
  { id: 3, name: 'Monitor', price: 300 },
  { id: 4, name: 'Keyboard', price: 75 }
];

To sort by price ascending (low to high), the subtraction method is clean and fast:

products.sort((a, b) => a.price - b.price);

For descending order (high to low), simply swap the operands:

products.sort((a, b) => b.price - a.price);

Why subtraction works: JavaScript coerces the result of the subtraction into a number. If a.price is 25 and b.price is 1200, the result is -1175 (negative), placing the mouse before the laptop. This approach is highly performant because it avoids verbose if/else blocks Turns out it matters..

Handling Nullish or Missing Values

Real-world data is messy. A property might be null, undefined, or missing entirely. Subtraction involving null results in NaN, which breaks the sort order (elements become "unordered") Turns out it matters..

products.sort((a, b) => {
  const valA = a.price ?? 0; // Treat null/undefined as 0
  const valB = b.price ?? 0;
  return valA - valB;
});

Alternatively, push nullish values to the end:

products.sort((a, b) => {
  if (a.price == null && b.price == null) return 0;
  if (a.price == null) return 1;  // a goes last
  if (b.price == null) return -1; // b goes last
  return a.price - b.price;
});

Sorting by String Properties

String comparison requires localeCompare() for correct alphabetical ordering, especially when dealing with accents, case sensitivity, or different locales. The default > and < operators compare UTF-16 code units, meaning uppercase 'Z' (90) comes before lowercase 'a' (97).

Basic Alphabetical Sort (Case-Insensitive)

const users = [
  { name: 'Charlie' },
  { name: 'alice' },
  { name: 'Bob' }
];

// Incorrect: ['Bob', 'Charlie', 'alice']
users.sort((a, b) => a.name.localeCompare(b.

The `sensitivity: 'base'` option ignores case and accents (e.g., 'a' === 'A' === 'á'). For strict dictionary ordering where case matters only as a tie-breaker, use `sensitivity: 'variant'` (default) or `sensitivity: 'case'`.

### Locale-Aware Sorting

Always pass the locale (e.Now, , `'en-US'`, `'de-DE'`, `'sv-SE'`) as the second argument to `localeCompare`. Swedish sorts 'z' before 'ö', while German sorts 'ö' like 'oe'. Which means g. Relying on the browser default (`undefined`) leads to inconsistent behavior across user environments.

```javascript
// German locale: 'ö' sorts near 'o'
items.sort((a, b) => a.label.localeCompare(b.label, 'de-DE'));

Sorting by Date Properties

Dates are best compared by converting them to timestamps (numbers) using getTime() or the unary + operator. This reduces the logic to a simple numeric subtraction.

const events = [
  { title: 'Launch', date: '2023-10-01' },
  { title: 'Planning', date: '2023-08-15' },
  { title: 'Review', date: '2023-09-20' }
];

// Ascending (Oldest first)
events.sort((a, b) => new Date(a.date) - new Date(b.

// Descending (Newest first)
events.sort((a, b) => new Date(b.date) - new Date(a.

**Performance Note:** Creating `new Date()` objects inside the comparator runs on every comparison (O(n log n) times). For large datasets, *pre-compute* the timestamps:

```javascript
const eventsWithTime = events.map(e => ({ ...e, timestamp: new Date(e.date).getTime() }));
eventsWithTime.sort((a, b) => a.timestamp - b.timestamp);

Multi-Level Sorting (Compound Keys)

Often, you need a primary sort key and a secondary tie-breaker. Take this: sort users by role (Admin > User > Guest), then by name alphabetically Easy to understand, harder to ignore..

The "Chain" Pattern

The most readable modern approach chains logical OR (||) operators. Since the comparator returns 0 for equality, the next comparison executes only when the previous one returns 0.

const roleOrder = { Admin: 3, User: 2, Guest: 1 };

users.That's why role] - roleOrder[a. sort((a, b) => 
  roleOrder[b.And name. role] || // Primary: Role descending
  a.localeCompare(b.

### Explicit If/Else Logic

For complex logic involving multiple conditions per level, explicit checks are clearer:

```javascript
users.sort((a, b) => {
  // 1. Sort by active status (active first)
  if (a.isActive !== b.isActive) return b.isActive - a.isActive; // true (1) > false (0)

  // 2. Sort by role priority
  const roleDiff = roleOrder[b.role] - roleOrder[a.role];
  if (roleDiff !

```javascript
  if (roleDiff !== 0) return roleDiff;

  // 3. name.Sort by name alphabetically
  return a.localeCompare(b.

### Handling Missing Values

Real-world data often contains `null` or `undefined`. Decide whether missing values sort first or last, and guard against them to avoid runtime errors:

```javascript
// Missing values sort last
products.sort((a, b) => {
  if (a.price == null) return 1;
  if (b.price == null) return -1;
  return a.price - b.price;
});

Sort Stability

Modern JavaScript engines guarantee stable sort (ES2019). Elements that compare equal retain their original relative order. This matters when sorting by multiple keys sequentially:

// Stable: preserves prior order for equal prices
items.sort((a, b) => a.category.localeCompare(b.category));
items.sort((a, b) => a.price - b.price);

Conclusion

Effective sorting in JavaScript comes down to choosing the right tool for the data type. That said, for compound keys, the || chain keeps comparators concise, while explicit if blocks handle detailed business logic. Always pre-compute expensive values for large datasets, guard against null/undefined, and rely on stable sort when layering multiple passes. Use simple subtraction for numbers, localeCompare with an explicit locale for strings, and timestamps for dates. With these patterns, your collections will order predictably across browsers and locales.

People argue about this. Here's where I land on it.

Performance: The Schwartzian Transform

When comparisons are expensive—such as complex locale-aware string sorting, parsing dates from strings, or calculating derived values—recomputing them for every comparison (O(n log n) times) kills performance. The Schwartzian Transform (Decorate-Sort-Undecorate) computes the sort key once per element.

// Slow: localeCompare runs O(n log n) times
const slow = [...data].sort((a, b) => 
  a.name.localeCompare(b.name, 'de-DE', { sensitivity: 'variant' })
);

// Fast: Decorate -> Sort -> Undecorate
const fast = data
  .Consider this: localeCompare(b. sortKey.Now, name // Or expensive computation: parseDate(item. Even so, rawDate) 
  }))
  . map(item => ({ 
    item, 
    sortKey: item.sort((a, b) => a.sortKey, 'de-DE'))
  .

**Rule of thumb:** If the comparator does more than a simple property access or arithmetic operation, decorate first.

## Immutability with `toSorted()`

ES2023 introduced `Array.prototype.Now, toSorted()`, returning a new array instead of mutating in place. This fits functional patterns and React/Redux state updates cleanly.

```javascript
const original = [3, 1, 2];
const sorted = original.toSorted((a, b) => a - b);

console.log(original); // [3, 1, 2] (unchanged)
console.log(sorted);   // [1, 2, 3]

Pair it with toReversed(), toSpliced(), and with() for fully immutable array workflows.

Optimizing Locale Comparison: Reuse Intl.Collator

Creating a Collator inside a comparator callback instantiates a new object on every comparison. Instantiate it once outside Most people skip this — try not to..

// Bad: New Collator every comparison
items.sort((a, b) => new Intl.Collator('de').compare(a.label, b.label));

// Good: Single instance
const collator = new Intl.Coll
More to Read

New Arrivals

Worth the Next Click

Related Reading

Thank you for reading about Js Sort Array Of Objects By Property. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home