---
title: "Sort array of objects by string property value in JavaScript"
description: "Sorting arrays of objects by a string property is a common task in JavaScript, especially when working with datasets in web applications. For example, you…"
url: https://www.danny.engineering/answer/javascript/sort-array-of-objects-by-string-property-value-in-javascript
author: Danny
published: 2025-02-04T00:00:00.000Z
updated: 2025-02-04T19:49:00.000Z
tags: ["Javascript"]
---

# Sort array of objects by string property value in JavaScript

Sorting arrays of objects by a string property is a common task in JavaScript, especially when working with datasets in web applications. For example, you might sort a list of employees by their names or organise products based on their categories in alphabetical order. JavaScript provides tools to handle this efficiently, but understanding how to implement the solution is key to avoiding common pitfalls.

## Problem  

Suppose you have an array of objects, and each object contains a property that is a string. You want to sort the array in ascending or descending order based on this string property. However:  

1. Sorting objects directly by properties requires implementing a custom comparison logic, as the default `sort()` method only works for primitive values.  
2. Case sensitivity (uppercase vs lowercase letters) and localisation can cause sorting to behave unexpectedly.  
3. Handling invalid or missing data (e.g., `null` or `undefined` values) requires careful handling to avoid runtime errors or incorrect results.  

Suppose ou have an array of user objects, and you need to sort them by their `name` property.

```javascript
const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Charlie' },
  { id: 3, name: 'Bob' },
];
```

Expected result when sorted ascending by `name` :  

```javascript
[
  { id: 1, name: 'Alice' },
  { id: 3, name: 'Bob' },
  { id: 2, name: 'Charlie' },
]
```

## Solution  

To sort an array of objects by a string property, you can use the `Array.prototype.sort()` method along with a custom compare function. Below are two different approaches to solving this problem.  

### Simple String Comparison  

This method compares the values of the specified string property directly using `localeCompare()`, which provides accurate lexicographical sorting.  

```javascript
const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Charlie' },
  { id: 3, name: 'Bob' },
];

// Sort by 'name' property (ascending)
users.sort((a, b) => a.name.localeCompare(b.name));

console.log(users);
// Output:
// [
//   { id: 1, name: 'Alice' },
//   { id: 3, name: 'Bob' },
//   { id: 2, name: 'Charlie' }
// ]
```

- The `localeCompare()` method performs case-insensitive string comparison based on the default locale.  
- It ensures proper handling of non-ASCII characters, such as accented letters (e.g., `è`, `é`).  
- Use `localeCompare()` for language-specific string sorting to avoid inconsistent ordering.  
- If sorting in descending order, swap the compare arguments: `b.name.localeCompare(a.name)`. 
- If `users[i].name` is `null` or `undefined`, `localeCompare()` may throw an error. Always validate your data.  

### Case-Insensitive Comparison and Custom Fallback  

Adding custom logic allows you to handle case sensitivity and prevent errors when properties are missing or invalid.  

```javascript
const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'charlie' }, // Notice lowercase 'c'
  { id: 3, name: 'bob' },     // Notice lowercase 'b'
  { id: 4, name: null }       // Missing name
];

// Sort by 'name' property (ascending), handling null values
users.sort((a, b) => {
  const nameA = (a.name || '').toLowerCase(); // Fallback to empty string
  const nameB = (b.name || '').toLowerCase();

  if (nameA < nameB) return -1;
  if (nameA > nameB) return 1;
  return 0; // Equal values
});

console.log(users);
// Output:
// [
//   { id: 1, name: 'Alice' },
//   { id: 3, name: 'bob' },
//   { id: 2, name: 'charlie' },
//   { id: 4, name: null }
// ]
```



- The `toLowerCase()` method ensures case-insensitive comparison.  
- `null` or `undefined` values are replaced with empty strings (`''`) to avoid errors.  
- Using `toLowerCase()` ensures uniform comparisons regardless of string case.  
- Always provide consistent fallback values for invalid data.  
- Replacing `null` or `undefined` with empty strings may not align with your desired sorting behaviour. Consider whether such objects should be filtered out or moved to the start/end of the array.  

## Further Considerations  

### Performance  
- Sorting an array has a time complexity of **O(n log n)**, which is generally efficient for moderate-sized arrays. However, for very large datasets, consider optimising performance by first checking whether sorting is necessary (e.g., if the data is already sorted).  

### Localisation  
- If your application involves users from different regions, always use `localeCompare()`. You can also specify a locale and options for more fine-grained control, e.g., `localeCompare(b.name, 'en', { sensitivity: 'base' })`.  

### Real-World Use Cases  
- Sorting user lists or directories alphabetically in UI components.  
- Ordering products on e-commerce platforms by category or brand name.  
- Sorting search results based on relevance or alphabetical fields like title.  

## Related Resources  

- [MDN Web Docs: Array.prototype.sort()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)  
- [MDN Web Docs: String.prototype.localeCompare()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare)  
- [JavaScript Sorting Best Practices](https://developer.mozilla.org/en-US/)
