Skip to content

Instantly share code, notes, and snippets.

@AndiSHFR
Last active June 22, 2017 08:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndiSHFR/9686298bfe6eb76d136d5252706d064d to your computer and use it in GitHub Desktop.
Save AndiSHFR/9686298bfe6eb76d136d5252706d064d to your computer and use it in GitHub Desktop.
Javascript code to show how to sort array of objects by object properties.
!function() {
function _dynamicSortMultiple(attr) {
/*
* save the arguments object as it will be overwritten
* note that arguments object is an array-like object
* consisting of the names of the properties to sort by
*/
var props = arguments;
return function (obj1, obj2) {
var i = 0, result = 0, numberOfProperties = props.length;
/* try getting a different result from 0 (equal)
* as long as we have extra properties to compare
*/
while(result === 0 && i < numberOfProperties) {
result = dynamicSort(props[i])(obj1, obj2);
i++;
}
return result;
}
}
function _dynamicSort(property) {
var sortOrder = 1;
if(property[0] === "-") {
sortOrder = -1;
property = property.substr(1);
}
return function (a,b) {
var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
return result * sortOrder;
}
}
Object.defineProperty(Array.prototype, "sortBy", {
enumerable: false,
writable: true,
value: function() {
return this.sort(_dynamicSortMultiple.apply(null, arguments));
}
});
}();
var People = [
{ Name: 'Andi', Surname: 'Schaefer' },
{ Name: 'Mike', Surname: 'Meyers' },
{ Name: 'Alim', Surname: 'Sinuk' }
];
console.log(People.sortBy("Name", "-Surname"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment