Last active
December 28, 2023 05:36
-
-
Save petergi/29145120dd8fdbe47362677f464739df to your computer and use it in GitHub Desktop.
Sorts an array of objects alphabetically based on a given property.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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