Created
March 3, 2017 07:17
-
-
Save monochromer/ecde4f324dbade97e2f0f428cf118361 to your computer and use it in GitHub Desktop.
function for dynamic sorting arrays
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
// http://www.sitepoint.com/sort-an-array-of-objects-in-javascript | |
const bands = [ | |
{ genre: 'Rap', band: 'Migos', albums: 2}, | |
{ genre: 'Pop', band: 'Coldplay', albums: 4, awards: 13}, | |
{ genre: 'Rock', band: 'Breaking Benjamins', albums: 1} | |
]; | |
// function for dynamic sorting | |
function compareValues(key, order='asc') { | |
return function(a, b) { | |
if(!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) { | |
// property doesn't exist on either object | |
return 0; | |
} | |
const varA = (typeof a[key] === 'string') ? | |
a[key].toUpperCase() : a[key]; | |
const varB = (typeof b[key] === 'string') ? | |
b[key].toUpperCase() : b[key]; | |
let comparison = 0; | |
if (varA > varB) { | |
comparison = 1; | |
} else if (varA < varB) { | |
comparison = -1; | |
} | |
return ( | |
(order == 'desc') ? (comparison * -1) : comparison | |
); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment