I have an array like this
var array = [{
order: 3,
sub - array: [{
order: 2
},{
order: 1
}]
},{
order: 2,
sub - array: [{
order: 2
},{
order: 1
}]
}];
Now I want to sort the the complete collection on the attribute order, so both the outer
as well as inner arrays should get sorted based on the attribute order.
The final output should look like this.
var array = [{
order: 2,
sub - array: [{
order: 1
},{
order: 2
}]
},{
order: 3,
sub - array: [{
order: 1
},{
order: 2
}]
}];
Matt
75.4k26 gold badges156 silver badges181 bronze badges
asked Jun 20, 2012 at 12:45
vijay tyagi
2,2563 gold badges20 silver badges32 bronze badges
-
1In future, please spend more time writing or formatting your post. Formatting help can be found hereMatt– Matt2012年06月20日 12:48:34 +00:00Commented Jun 20, 2012 at 12:48
-
possible duplicate of How to sort an array of javascript objects?Rob W– Rob W2012年06月20日 12:50:20 +00:00Commented Jun 20, 2012 at 12:50
-
@jbabey structure can be any number of levels deep, sorry didn't get the accept answers part.vijay tyagi– vijay tyagi2012年06月20日 13:11:11 +00:00Commented Jun 20, 2012 at 13:11
2 Answers 2
var propertySort = function(a, b){
return a.order > b.order ? 1 : (a.order < b.order ? -1 : 0);
}
var reorder = function(arr){
var l = arr.length;
while (l--){
if (arr[l]['sub-array']){
reorder(arr[l]['sub-array']);
}
}
arr.sort(propertySort);
};
reorder(arr);
console.log(arr);
This should re-order the array for any number of nested levels.
answered Jun 20, 2012 at 12:55
Graham
6,5722 gold badges39 silver badges39 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Use Array.prototype.sort and call it on array and subsequently on each element of array with an appropriate compare function.
Something like this should work:
array.sort(function (e1, e2) {
return (e1.order - e2.order);
});
array.forEach(function(e) {
e["sub-array"].sort(function (e1, e2) {
return (e1.order - e2.order);
});
});
answered Jun 20, 2012 at 12:49
Daniel Baulig
11.1k7 gold badges47 silver badges45 bronze badges
Comments
Explore related questions
See similar questions with these tags.
lang-js