Skip to content

Instantly share code, notes, and snippets.

@mir4ef
Last active June 7, 2017 13:23
Show Gist options
  • Save mir4ef/d89ea07bad13f32b704eab2c64ce1ceb to your computer and use it in GitHub Desktop.
Save mir4ef/d89ea07bad13f32b704eab2c64ce1ceb to your computer and use it in GitHub Desktop.
Sorting an object with mixed content (numbers && letters)
// 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'));
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