DEV Community

Cover image for How to sort an array of objects in JavaScript?
ThemeSelection for ThemeSelection

Posted on

How to sort an array of objects in JavaScript?

Sorting an array of objects is something you’ll run into pretty often when working with JavaScript. This usually comes up when dealing with tables, lists, or data coming from an API.

In this article, we’ll go through how to sort arrays of objects using JavaScript’s sort() method. We’ll focus on practical examples and common patterns you’re likely to use in real projects.

Why Sorting Arrays of Objects Matters

In most applications, data doesn’t arrive in the order you want. API responses, database results, or user-generated content are usually unsorted, so you have to handle that yourself before showing anything on the screen.

Sorting becomes especially useful when rendering table rows, listing products by name or price, or showing users alphabetically. A small detail like correct ordering can make a UI feel much easier to use.

It also helps prevent bugs. If you don’t understand how sorting works, it’s easy to accidentally mutate data, get unexpected orderings, or end up with sorting logic that’s hard to change later.

Understanding the sort() Method

JavaScript’s sort() method reorders the elements of an array. When you’re sorting objects, you provide a comparison function that tells JavaScript how two items should be compared.

The comparison function receives two elements and returns:

  • a negative value → a comes before b
  • a positive value → b comes before a
  • 0 → no change in order
array.sort((a, b) => {
  // return negative, positive, or 0
});

Enter fullscreen mode Exit fullscreen mode

One important thing to remember: sort() mutates the original array. This often catches people off guard, especially when working with state or reused data.

Sorting by Object Properties

Most of the time, you won’t sort objects directly. Instead, you’ll sort based on one of their properties like a name, price, or date.

Here are the most common cases.

Sorting by String Properties

This is very common when dealing with names, titles, or labels.
Enter fullscreen mode Exit fullscreen mode

Basic string sorting:

users.sort((a, b) => a.name.localeCompare(b.name));

Enter fullscreen mode Exit fullscreen mode

Case-insensitive sorting:

users.sort((a, b) =>
  a.name.toLowerCase().localeCompare(b.name.toLowerCase())
);

Enter fullscreen mode Exit fullscreen mode

Descending order:

users.sort((a, b) => b.name.localeCompare(a.name));

Enter fullscreen mode Exit fullscreen mode

Using localeCompare() is generally safer than manual string comparisons and gives more consistent results.

Sorting by Numeric and Date Properties

Numbers are simpler to deal with.

**Numeric sorting:**
Enter fullscreen mode Exit fullscreen mode
```jsx
products.sort((a, b) => a.price - b.price);

```
Enter fullscreen mode Exit fullscreen mode
For dates stored as strings, convert them to `Date` objects before comparing.

**Sorting date strings:**
Enter fullscreen mode Exit fullscreen mode
```jsx
events.sort((a, b) => new Date(a.date) - new Date(b.date));

```
Enter fullscreen mode Exit fullscreen mode
This avoids incorrect ordering that can happen with plain string comparison.
Enter fullscreen mode Exit fullscreen mode

Codepen Example: [Sort an array of objects]


Checkout the best Bootstrap Templates for developers for building responsive web apps easily.

Sneat dashboard pro bootstrap


Creating a Dynamic Sort Function

In real projects, you rarely sort by just one field. Sometimes it’s the name, sometimes the price, sometimes a date. Writing a new comparison function every time gets repetitive.

A small utility function can help with that.

function sortBy(key, order = "asc") {
  return (a, b) => {
    if (typeof a[key] === "string") {
      return order === "asc"
        ? a[key].localeCompare(b[key])
        : b[key].localeCompare(a[key]);
    }

    return order === "asc"
      ? a[key] - b[key]
      : b[key] - a[key];
  };
}

Enter fullscreen mode Exit fullscreen mode

Usage:

users.sort(sortBy("name"));
products.sort(sortBy("price", "desc"));

Enter fullscreen mode Exit fullscreen mode

This isn’t meant to cover every edge case, but it works well for most simple lists and keeps the calling code readable.

Best Practices & Common Mistakes

A few things worth keeping in mind:

  • Don’t mutate the original array if you still need it elsewhere:

    const sortedUsers = [...users].sort(sortBy("name"));
    
    
  • Use localeCompare() for strings instead of custom logic.

  • Watch out for missing or undefined values when sorting real data.

  • Be careful when sorting mixed types (for example, numbers stored as strings).

Conclusion

Sorting arrays of objects is a regular part of working with JavaScript. Once you understand how sort() and comparison functions work, most use cases are pretty straightforward.

For simple needs, a direct sort() call is enough. As things grow, a reusable sort helper can make your code cleaner and easier to maintain. Knowing both approaches helps you handle real-world data without overcomplicating things.

Top comments (0)