Last active
October 14, 2018 07:02
-
-
Save Phoenix2k/f027bc8ab53e0e43b404acc917975d4a to your computer and use it in GitHub Desktop.
JavaScript - Sort an array of objects according to a specific key
This file contains hidden or 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
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