Last active
June 7, 2017 13:23
-
-
Save mir4ef/d89ea07bad13f32b704eab2c64ce1ceb to your computer and use it in GitHub Desktop.
Sorting an object with mixed content (numbers && letters)
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
// from https://www.sitepoint.com/sort-an-array-of-objects-in-javascript/ | |
function compareValues(key, order='asc') { | |
return function(a, b) { | |
if(!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) { | |
return 0; | |
} | |
const valA = (typeof a[key] === 'string') ? a[key].toUpperCase() : a[key]; | |
const valB = (typeof b[key] === 'string') ? b[key].toUpperCase() : b[key]; | |
let comparison = 0; | |
if (valA > valB) { | |
comparison = 1; | |
} else if (valA < valB) { | |
comparison = -1; | |
} | |
return ((order === 'desc') ? (comparison * -1) : comparison); | |
}; | |
} | |
arr.sort(compareValues('key', 'desc')); |
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
function objSort(a, b) { | |
const valA = a[column].value; | |
const valB = b[column].value; | |
if (!valA && !valB) { | |
return 0; | |
} | |
if (!valA) { | |
return -1; | |
} | |
if (!valB) { | |
return 1; | |
} | |
if (isNaN(valA) && isNaN(valB)) { | |
return valA.localeCompare(valB); | |
} else { | |
if (valA === valB) { | |
return 0; | |
} | |
return valA > valB ? 1 : -1; | |
} | |
} | |
arr.sort(objSort); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment