Skip to content

Instantly share code, notes, and snippets.

@Phoenix2k
Last active October 14, 2018 07:02
Show Gist options
  • Save Phoenix2k/f027bc8ab53e0e43b404acc917975d4a to your computer and use it in GitHub Desktop.
Save Phoenix2k/f027bc8ab53e0e43b404acc917975d4a to your computer and use it in GitHub Desktop.
JavaScript - Sort an array of objects according to a specific key
const data = [
{ "name": "A" },
{ "name": "C" },
{ "name": "B" },
{ "name": "D" }
];
/**
* sortObjectArrayByKey
*
* Sorts array of objects according to a specific key.
*
* @param {array} Array of objects
* @param {string} Key to look for in the array of objects
* @param {string} Direction `asc` or `desc`. Defaults to `asc`.
*/
function sortObjectArrayByKey( data, key, direction ) {
return 'desc' === direction ? data.sort(function( a, b ) {
return a[ key ] < b[ key ] ? 1 : a[ key ] > b[ key ] ? -1 : 0;
}) : data.sort(function( a, b ) {
return a[ key ] < b[ key ] ? -1 : a[ key ] > b[ key ] ? 1 : 0;
});
}
console.log( 'Sorted data:', sortObjectArrayByKey( data, 'name', 'asc' ) );
// [ { "name": "A" }, { "name": "B" }, { "name": "C" }, { "name": "D" } ];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment