Skip to content

Instantly share code, notes, and snippets.

@gtchakama
Created April 13, 2023 18:06
Show Gist options
  • Save gtchakama/9cc7076d5b4957f2f08ba0487ef53860 to your computer and use it in GitHub Desktop.
Save gtchakama/9cc7076d5b4957f2f08ba0487ef53860 to your computer and use it in GitHub Desktop.
Sort an array of objects by a specified property.
/**
* Sorts an array of objects by a specified property
*
* @param {Array} array - The array to sort
* @param {string} property - The property to sort by
* @returns {Array} - The sorted array
*/
const sortByProperty = (array, property) => {
return array.sort((a, b) => {
if (a[property] < b[property]) {
return -1;
}
if (a[property] > b[property]) {
return 1;
}
return 0;
});
};
// Example usage:
const myArray = [
{ name: "John", age: 30 },
{ name: "Jane", age: 25 },
{ name: "Bob", age: 35 }
];
const sortedArray = sortByProperty(myArray, 'age');
console.log(sortedArray);
@gtchakama
Copy link
Author

  • the sortByProperty function takes an array and a property as parameters and returns a sorted array based on that property.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment