I'm trying to sort an array of javascript objects by their properties for an angularjs application. I need to be able to sort by Numbers and Strings.
So far i have expanded the filter from Armin provided in this thread to sort numbers and strings (see code below).
What i am still missing is the ability to give a nested property (like user.surname) to the filter. It should be dynamic, so that i would be able to provide any depth of nested properties to it. Is there a way to do this?
Here's my filter code:
angular.module('app')
.filter('orderObjectBy', function(){
return function(input, filterBy) {
if (!angular.isObject(input)) return input;
var attribute = filterBy;
var reverse = false;
if (filterBy.substr(0,1) == '-') {
attribute = filterBy.substr(1);
reverse = true;
}
var array = [];
for(var objectKey in input) {
array.push(input[objectKey]);
}
if (parseInt(array[0][attribute])) {
array.sort(function(a, b){
a = parseInt(a[attribute]);
b = parseInt(b[attribute]);
return a - b;
});
} else {
array.sort(function (a,b) {
if (a[attribute] < b[attribute]) {
return -1;
} else if (a[attribute] > b[attribute]) {
return 1;
} else {
return 0;
}
});
}
if (reverse) {
return array.reverse();
} else {
return array;
}
}
});
orderByfilter on an array of objects, and the filtering is done on a property. How's that different from your problem ? The thread you mention is talking about sorting properties of an object ... not an array of objects.