Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
83
rated 0 times [  87] [ 4]  / answers: 1 / hits: 51821  / 14 Years ago, tue, february 22, 2011, 12:00:00

I have this function to sort a JavaScript array of objects based on a property:



// arr is the array of objects, prop is the property to sort by
var sort = function (prop, arr) {
arr.sort(function (a, b) {
if (a[prop] < b[prop]) {
return -1;
} else if (a[prop] > b[prop]) {
return 1;
} else {
return 0;
}
});
};


It works with arrays like this:



sort('property', [
{property:'1'},
{property:'3'},
{property:'2'},
{property:'4'},
]);


But I want to be able to sort also by nested properties, for example something like:



sort('nestedobj.property', [
{nestedobj:{property:'1'}},
{nestedobj:{property:'3'}},
{nestedobj:{property:'2'}},
{nestedobj:{property:'4'}}
]);


However this doesn't work because it is not possible to do something like object['nestedobj.property'], it should be object['nestedobj']['property'].



Do you know how could I solve this problem and make my function work with properties of nested objects?



Thanks in advance


More From » arrays

 Answers
13

You can split the prop on ., and iterate over the Array updating the a and b with the next nested property during each iteration.



Example: http://jsfiddle.net/x8KD6/1/



var sort = function (prop, arr) {
prop = prop.split('.');
var len = prop.length;

arr.sort(function (a, b) {
var i = 0;
while( i < len ) { a = a[prop[i]]; b = b[prop[i]]; i++; }
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
});
return arr;
};

[#93640] Saturday, February 19, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
margaritakristinak

Total Points: 502
Total Questions: 127
Total Answers: 98

Location: England
Member since Mon, May 17, 2021
3 Years ago
;