Skip to content

Instantly share code, notes, and snippets.

@petergi
Last active December 28, 2023 05:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petergi/29145120dd8fdbe47362677f464739df to your computer and use it in GitHub Desktop.
Save petergi/29145120dd8fdbe47362677f464739df to your computer and use it in GitHub Desktop.
Sorts an array of objects alphabetically based on a given property.
// Removed the localeCompare function call
// Replaced it with a more efficient comparison using the less-than and greater-than operators.
// This avoids the overhead of string comparison and should make the function faster.
/**
* Sorts an array of objects alphabetically based on a specified getter function.
*
* @param {Array} arr - The array to be sorted.
* @param {Function} getter - The getter function used to retrieve the value to compare.
* @param {string} [order="asc"] - The order in which to sort the array. Default is "asc" (ascending).
* @return {Array} - The sorted array.
*/
function alphabetical(arr, getter, order = "asc") {
return arr.sort((a, b) => {
const aValue = getter(a)
const bValue = getter(b)
if (aValue === bValue) return 0
return order === "asc" ? (aValue < bValue ? -1 : 1) : (aValue > bValue ? -1 : 1)
})
}
const people = [ { name: 'John' }, { name: 'Adam' }, { name: 'Mary' } ]
alphabetical(people, g => g.name) //= [ { name: 'Adam' }, { name: 'John' }, { name: 'Mary' } ]
alphabetical(people, g => g.name, 'desc') //= [ { name: 'Mary' }, { name: 'John' }, { name: 'Adam' } ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment