Join the Stack Overflow Community
Stack Overflow is a community of 6.3 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

Today I was asked to add sorting to a datatable in Angular. I have tried to use the built in orderBy filter, but it doesn't look like it can handle jagged data.

I need to be able to sort all the columns in the table, although I am having a problem with finding a way to sort values within the array.

Here is the simplified data I am dealing with:

[
  {
    "id": 1,
    "some_data": {
        "nested_id": 3,
        "nested_array": [
            {
                "id": 10,
                "some_value": "test3",
                "another_value": 1
            },
            {
                "id": 10,
                "some_value": "test2",
                "another_value": 1
            }
        ]
    }
},
{
    "id": 2,
    "some_data": {
        "nested_id": 5,
        "nested_array": [
            {
                "id": 10,
                "some_value": "test1",
                "another_value": 1
            }
        ]
    }
  }
]

Could anybody point me in the right direction how would I write a generic method that is able to sort the following array on any property? I know how to sort it based on "id" and "nested_id", but what about "some_value"?

EDIT:

I tried something similar to this, but that would only work on the outer properties, not the properties within the "nested_array".

The result I am trying to achieve is that when I sort on "some_value", it should display object with "id" of 2 first, then object with "id" of 1 and objects within "nested_array" should also change their order.

function sortBy(prop){
 return function(a,b){
  if( a[prop] > b[prop]){
      return 1;
  }else if( a[prop] < b[prop] ){
      return -1;
  }
  return 0;
 }
}
share|improve this question
    
The sort function in the prototype of array is a good start. You just need to also declare a variable (which is accessible from the function you pass to sort) to hold the name of the parameter to sort by. – Alvin Thompson Nov 4 at 14:28
    
what part would you like to sort? please add the wanted result. – Nina Scholz Nov 4 at 14:29
    
Add to the answer the logic you are trying to sort by, and what is the expected result. Also add your own work - the code that didn't work. – Ori Drori Nov 4 at 14:30
    
What array do you want to sort nested_array ? – kevin ternet Nov 4 at 14:32
1  
@problematic ok so if you want to sort with id, it should sort by id for outer and inner properties? – kukkuz Nov 4 at 16:07

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.