Logo

How to sort array of objects by string property value?

Comprehensive Guide to Sorting an Array of Objects by a String Property in JavaScript

Sorting an array of objects by a specific property is a common requirement in applications where you need to display data in a particular order—such as sorting a list of products by name, or arranging employees by their last names. In JavaScript, the built-in Array.prototype.sort() method provides a flexible way to handle these sorting tasks.

The sort() Method Basics

The sort() method in JavaScript sorts elements of an array in place, meaning it modifies the original array. It takes an optional comparison function as an argument. Without a comparison function, sort() converts elements to strings and sorts them lexicographically, which often isn’t suitable when dealing with objects.

When sorting an array of objects, you’ll typically provide a comparison function that:

  1. Extracts the property values you want to compare.
  2. Returns a negative number if the first object should appear before the second, a positive number if it should appear after, or zero if they are equal.

Example Scenario

Suppose you have an array of user objects, each having a name property, and you want to sort them by the name in ascending order:

const users = [ { name: "Charlie", age: 30 }, { name: "Alice", age: 25 }, { name: "bob", age: 28 } ];

We want the result to be ordered by the name property, so that the output is [ { name: "Alice", ... }, { name: "bob", ... }, { name: "Charlie", ...} ].

Writing the Comparison Function

The comparison function you provide to sort() should look like this:

users.sort((a, b) => { // Extract the name properties const nameA = a.name; const nameB = b.name; // Compare the strings if (nameA < nameB) { return -1; // a should come before b } else if (nameA > nameB) { return 1; // a should come after b } else { return 0; // a and b are equal in terms of sorting } });

How This Works:

  • If nameA < nameB, we return -1, indicating that the first element (a) should be placed before the second element (b) in the sorted array.
  • If nameA > nameB, we return 1, meaning a goes after b.
  • If they are equal, we return 0, which leaves their order unchanged relative to each other.

Dealing with Case Sensitivity

By default, string comparisons are case-sensitive. In the example above, "bob" would come after "Charlie" because lowercase letters have a higher Unicode value than uppercase letters. To achieve a case-insensitive sort, convert both strings to a common case (either both lowercase or both uppercase) before comparing:

users.sort((a, b) => { const nameA = a.name.toLowerCase(); const nameB = b.name.toLowerCase(); if (nameA < nameB) return -1; if (nameA > nameB) return 1; return 0; });

Now "bob" will come before "Charlie" because "bob".toLowerCase() ("bob") is alphabetically before "charlie".

Final Example

Putting it all together, the final code might look like:

const users = [ { name: "Charlie", age: 30 }, { name: "Alice", age: 25 }, { name: "bob", age: 28 } ]; users.sort((a, b) => { const nameA = a.name.toLowerCase(); const nameB = b.name.toLowerCase(); if (nameA < nameB) return -1; if (nameA > nameB) return 1; return 0; }); console.log(users); // Output: // [ // { name: "Alice", age: 25 }, // { name: "bob", age: 28 }, // { name: "Charlie", age: 30 } // ]

This result is now alphabetically sorted, ignoring case.

Stability of Sorting

ECMAScript (ES) 2019 and later specifies that the built-in sort() method is stable. A stable sort means that if two elements are considered equal based on the comparison function, their relative order remains the same as in the original array. This can be important if you have multiple sorting criteria or want to maintain the original order for items deemed equal.

Additional Tips

  • If you need descending order, you can simply invert the logic:
    if (nameA < nameB) return 1; if (nameA > nameB) return -1; return 0;
  • For multi-criteria sorting (e.g., sort by name and then by age if names are the same), perform additional comparisons if the first criteria return equality:
    if (nameA === nameB) { // Then compare age or another property return a.age - b.age; }

Strengthening Your JavaScript Skills

Sorting arrays of objects is just one of many essential skills in JavaScript. To fully master such tasks, a strong foundation in the language’s features, data structures, and modern best practices is crucial.

  • Grokking JavaScript Fundamentals: This comprehensive course is perfect for beginners and those looking to refine their JavaScript skills. You’ll learn how to handle arrays, objects, and advanced operations like sorting, filtering, and mapping—setting you up for success in real-world projects.

In Summary

  1. Use the sort() method with a custom comparison function to sort objects by a string property.
  2. Convert strings to a common case (e.g., lowercase) for case-insensitive sorting.
  3. Return -1, 1, or 0 from the comparison function to determine the order.
  4. Leverage stable sorting (ES2019+) and multi-criteria sorting when needed.

With these principles, you’ll be able to sort arrays of objects by their string properties efficiently and effectively.

TAGS
Java
JavaScript
CONTRIBUTOR
TechGrind