Example: Sorting Array of Objects
We have an array of objects, each containing firstName and lastName properties. We want to sort the array based on the firstName property in both ascending and descending order.
// Define the array of objects
var objs = [
{ firstName: 'A', lastName: 'Mark' },
{ firstName: 'E', lastName: 'askavy' },
{ firstName: 'C', lastName: 'peter' }
];
// Sort in Ascending Order by 'firstName'
objs.sort((a, b) => a.firstName.localeCompare(b.firstName));
console.log("Sorted in Ascending Order by 'firstName':", objs);
// Sort in Descending Order by 'firstName'
objs.sort((a, b) => b.firstName.localeCompare(a.firstName));
console.log("Sorted in Descending Order by 'firstName':", objs);
Explanation
-
localeCompare:- This method is used to compare two strings. It is ideal for sorting as it handles case sensitivity and different locales.
-
Sorting Ascending:
-
a.firstName.localeCompare(b.firstName)ensures objects withfirstNamevalues are ordered alphabetically from A to Z.
-
-
Sorting Descending:
- Reversing the comparison to
b.firstName.localeCompare(a.firstName)sorts the objects in reverse order (Z to A).
- Reversing the comparison to
Example Output
Sorted in Ascending Order (A → Z):
[
{ firstName: 'A', lastName: 'Mark' },
{ firstName: 'C', lastName: 'peter' },
{ firstName: 'E', lastName: 'askavy' }
]
Sorted in Descending Order (Z → A):
[
{ firstName: 'E', lastName: 'askavy' },
{ firstName: 'C', lastName: 'peter' },
{ firstName: 'A', lastName: 'Mark' }
]
Sorting by lastName
You can extend this logic to sort by lastName if needed, by simply replacing firstName with lastName:
// Sort in Ascending Order by 'lastName'
objs.sort((a, b) => a.lastName.localeCompare(b.lastName));
console.log("Sorted in Ascending Order by 'lastName':", objs);
// Sort in Descending Order by 'lastName'
objs.sort((a, b) => b.lastName.localeCompare(a.lastName));
console.log("Sorted in Descending Order by 'lastName':", objs);
Example Output for lastName
Sorted in Ascending Order by lastName:
[
{ firstName: 'E', lastName: 'askavy' },
{ firstName: 'A', lastName: 'Mark' },
{ firstName: 'C', lastName: 'peter' }
]
Sorted in Descending Order by lastName:
[
{ firstName: 'C', lastName: 'peter' },
{ firstName: 'A', lastName: 'Mark' },
{ firstName: 'E', lastName: 'askavy' }
]
Tips
-
Case Sensitivity:
localeCompareensures sorting works regardless of case. -
Chaining Comparisons: For more complex sorting (e.g., sorting by
lastNamefirst, thenfirstName), you can chain comparisons:
objs.sort((a, b) =>
a.lastName.localeCompare(b.lastName) ||
a.firstName.localeCompare(b.firstName)
);
Top comments (0)