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;
}
}
sort
function in the prototype ofarray
is a good start. You just need to also declare a variable (which is accessible from the function you pass tosort
) to hold the name of the parameter to sort by. – Alvin Thompson Nov 4 at 14:28id
, it should sort byid
for outer and inner properties? – kukkuz Nov 4 at 16:07