Sort Array of Objects by Property in JavaScript: A Practical Guide

Learn practical JavaScript techniques to sort an array of objects by a property, including numeric and string comparisons, null handling, and multi-key sorting for data.

JavaScripting
JavaScripting Team
·5 min read
Quick AnswerSteps

To sort an array of objects by a property in JavaScript, use Array.prototype.sort with a comparator that compares the target property. For numbers, subtract to get ascending order; for strings, use localeCompare; handle missing values safely and consider multi-key sorts for stable results. If you need to preserve the original array, clone first.

Understanding the problem: sorting objects by a property

When working with datasets in JavaScript, you often need to sort an array of objects by a specific property. The most common approach is to use Array.prototype.sort with a comparator that inspects the target property on two objects. This section demonstrates the core idea and explains why a comparator function is essential. The goal is to return a negative value if a should come before b, a positive value if it should come after, or zero if they are equal. To illustrate, consider a simple array of users where you want to order by id in ascending order.

JavaScript
const users = [ { id: 3, name: "Alex" }, { id: 1, name: "Jess" }, { id: 2, name: "Sam" } ]; users.sort((a, b) => a.id - b.id); console.log(users);

Explanation:

  • The comparator (a, b) => a.id - b.id returns a negative number when a.id < b.id, placing a before b.
  • If ids are equal, the function returns 0 and preserves relative order (in engines with stable sort).
  • This pattern generalizes to any numeric property.

contextShortened2WeWillNotRemoveThisMarkerThisIsJustATlaceholder

Steps

Estimated time: 40-60 minutes

  1. 1

    Identify sort criteria

    Determine which property to sort by and whether the sort should be ascending or descending. Also consider how to handle missing values, nulls, or non-comparable types.

    Tip: Document the target property and expected order before writing code.
  2. 2

    Write a numeric comparator

    If sorting by a number (e.g., id, age, score), implement a comparator that returns a negative, zero, or positive value based on a.id - b.id.

    Tip: Keep the comparator focused on a single property for readability.
  3. 3

    Handle strings with localeCompare

    For string properties (e.g., name, city), use localeCompare to respect locale rules.

    Tip: localeCompare is locale-aware and returns -1, 0, or 1.
  4. 4

    Support dynamic properties

    If the property name is variable, access it with bracket notation and guard against undefined values.

    Tip: Use a[prop] and type checks to avoid runtime errors.
  5. 5

    Test with edge cases

    Test with missing properties, null values, and mixed data types to ensure robustness.

    Tip: Include at least one test for descending order.
Pro Tip: Clone the array prior to sorting if you need to preserve the original order.
Warning: Sorting mutates the array in place in JavaScript; use slice() or [...arr] to create a copy.
Note: For large datasets, numeric comparisons are faster than localeCompare on every element.

Prerequisites

Required

  • Required
  • Modern browser or Node.js environment for testing
    Required
  • Basic knowledge of arrays and objects in JavaScript
    Required
  • Understanding of comparator functions for Array.prototype.sort
    Required

Keyboard Shortcuts

ActionShortcut
CopyCopy code or text in editorCtrl+C
PastePaste into editor or consoleCtrl+V
UndoUndo last changeCtrl+Z
FindSearch within the documentCtrl+F
Comment/Uncomment lineToggle line comment in most editorsCtrl+/
Format documentAuto-format code in many editorsCtrl++I

Questions & Answers

How do I sort by a numeric property in ascending order?

Use a comparator that subtracts: arr.sort((a,b) => a.prop - b.prop). This returns a negative value when a should come first. For descending order, swap a and b or negate the result.

Use a simple numeric subtraction in the comparator; swap the operands for descending order.

How can I sort by a string property while respecting locale rules?

Use localeCompare: arr.sort((a,b) => a.name.localeCompare(b.name)). localeCompare returns a negative, zero, or positive number based on locale-aware order.

Use localeCompare for string properties to respect locale rules.

Does Array.prototype.sort mutate the original array?

Yes, sort mutates the array in place. To keep the original array intact, clone it first (e.g., const sorted = arr.slice()).

Yes, sort changes the original array unless you clone it first.

How do I sort by multiple properties?

Sort by the primary key; if equal, return the comparison result of the secondary key. This can be implemented in a single comparator or by using a stable sort twice.

Sort by the main key, then break ties with a second key.

What if some objects lack the property I’m sorting by?

Guard against undefined by providing a default (e.g., const va = a[prop] ?? 0). If you’re sorting strings, use an empty string as the fallback.

Provide sensible defaults to prevent runtime errors.

Is sort guaranteed to be stable across all environments?

Historically not guaranteed in all engines, but modern engines implement stable sort. When stability matters, clone the array and perform a two-pass sort or use a stable sort utility.

Modern environments are mostly stable, but assume stability carefully.

What to Remember

  • Sort using a comparator with Array.prototype.sort
  • Use numeric subtraction for numbers
  • Use localeCompare for strings
  • Guard against undefined values and use immutable patterns
  • Sort by multiple keys by chaining comparisons

Related Articles