Skip to content

Instantly share code, notes, and snippets.

@afmicc
Created September 21, 2018 01:54
Show Gist options
  • Save afmicc/5f11361f795e07539422cffe36b9cee6 to your computer and use it in GitHub Desktop.
Save afmicc/5f11361f795e07539422cffe36b9cee6 to your computer and use it in GitHub Desktop.
Sort array by properties
/*
* property: sort by property (name) - type: string
* property2: then sort by property2 (name) - type: string - optional
* areNumbers: Are property and property2 numbers? - type: boolean - optional
*/
Array.prototype.sortBy = function(property, property2, areNumbers)
{
return this.sort(function(a,b)
{
var valueA = areNumbers ? 0 : "";
var valueB = areNumbers ? 0 : "";
if (property)
{
valueA = areNumbers ?
(a[property] && !isNaN(a[property]) ? +a[property] : Number.MIN_SAFE_INTEGER) :
(a[property] ? a[property] + "" : "").toUpperCase();
valueB = areNumbers ?
(b[property] && !isNaN(b[property]) ? +b[property] : Number.MIN_SAFE_INTEGER) :
(b[property] ? b[property] + "" : "").toUpperCase();
if (property2)
{
var valueA2 = areNumbers ?
(a[property2] && !isNaN(a[property2]) ? +a[property2] : Number.MIN_SAFE_INTEGER) :
(a[property2] ? a[property2] + "" : "").toUpperCase();
var valueB2 = areNumbers ?
(b[property2] && !isNaN(b[property2]) ? +b[property2] : Number.MIN_SAFE_INTEGER) :
(b[property2] ? b[property2] + "" : "").toUpperCase();
if (valueA == valueB)
return (valueA2 < valueB2) ? -1 : (valueA2 > valueB2) ? 1 : 0;
else
return (valueA < valueB) ? -1 : (valueA > valueB) ? 1 : 0;
}
else
{
return (valueA < valueB) ? -1 : (valueA > valueB) ? 1 : 0;
}
}
else
{
valueA = areNumbers ?
(a ? +a : Number.MIN_SAFE_INTEGER) :
(a ? a + "" : "").toUpperCase();
valueB = areNumbers ?
(b ? +b : Number.MIN_SAFE_INTEGER) :
(b ? b + "" : "").toUpperCase();
}
return (valueA < valueB) ? -1 : (valueA > valueB) ? 1 : 0;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment