How to sort array of objects by string property value in JavaScript?

To sort an array of objects by a string property value in JavaScript, use the Array.prototype.sort() method with a custom comparator that leverages localeCompare(). Here’s how to implement it:

1. Basic Ascending Sort (Case-Sensitive)

const items = [
  { name: 'Charlie', age: 35 },
  { name: 'alice', age: 30 },
  { name: 'Bob', age: 25 }
];

// Sort by 'name' (case-sensitive)
items.sort((a, b) => a.name.localeCompare(b.name));

// Result:
// [
//   { name: 'Bob', age: 25 },
//   { name: 'Charlie', age: 35 },
//   { name: 'alice', age: 30 } (case-sensitive order)
// ]

2. Case-Insensitive Sort

items.sort((a, b) => 
  a.name.localeCompare(b.name, undefined, { sensitivity: 'base' })
);
// Result:
// [
//   { name: 'alice', age: 30 },
//   { name: 'Bob', age: 25 },
//   { name: 'Charlie', age: 35 }
// ]

3. Descending Order

items.sort((a, b) => 
  b.name.localeCompare(a.name) // Swap a and b for descending
);

4. Handle Missing/Undefined Properties

items.sort((a, b) => {
  const nameA = a.name || ''; // Treat missing `name` as empty string
  const nameB = b.name || '';
  return nameA.localeCompare(nameB);
});

5. Sort with Specific Locale (e.g., German)

items.sort((a, b) => 
  a.name.localeCompare(b.name, 'de', { ignorePunctuation: true })
);

Key Notes

  • Immutable Sort: To avoid modifying the original array, create a copy first:
  const sorted = [...items].sort((a, b) => a.name.localeCompare(b.name));
  • Stability: Modern JavaScript engines (ES2019+) use a stable sort algorithm, preserving order of equal elements.
  • Performance: localeCompare() is efficient for most cases, but avoid complex logic inside the comparator.

Edge Cases

ScenarioHandling
Null/Undefined ValuesUse || '' to default to empty string.
Non-String ValuesConvert to string: String(a.name).
Accented CharactersUse locale-specific localeCompare options.

Example with Dynamic Property

For a reusable function that sorts by any property:

function sortByProperty(arr, prop, order = 'asc') {
  return [...arr].sort((a, b) => {
    const valA = a[prop] || '';
    const valB = b[prop] || '';
    return order === 'asc' 
      ? valA.localeCompare(valB) 
      : valB.localeCompare(valA);
  });
}

// Usage
const sortedByName = sortByProperty(items, 'name', 'desc');

Result

The array is sorted by the specified string property, with options for case sensitivity, locale, and direction. Use localeCompare for accurate linguistic sorting!

Leave a Reply

Your email address will not be published. Required fields are marked *