Created
April 13, 2023 18:06
-
-
Save gtchakama/9cc7076d5b4957f2f08ba0487ef53860 to your computer and use it in GitHub Desktop.
Sort an array of objects by a specified 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
/** | |
* 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); |
Author
gtchakama
commented
Apr 13, 2023
- 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