Reputation: 392
I have a nested array and want to sort it by a key present inside the inner array.
below given is my array which I want to sort using NSSortDescriptor
or in other way.
fares(
{
pid = 1;
type1 = (
{
color = "red";
size = "big";
properties = (
{
mod = "auto";
payment = "EMI";
moresegs = (
{
id = 141;
name = "abcd";
duration = "1 year"
})
})
});
type2 = (
{
color = "green";
size = "small";
properties = (
{
mod = "auto";
payment = "EMI";
moresegs = (
{
id = 141;
name = "abcd";
duration = "1 year"
})
})
})
}
{
pid = 1;
type1 = (
{
color = "red";
size = "big";
properties = (
{
mod = "auto";
payment = "EMI";
moresegs = (
{
id = 141;
name = "abcd";
duration = "1 year"
})
})
});
type2 = (
{
color = "green";
size = "big";
properties = (
{
mod = "auto";
payment = "EMI";
moresegs = (
{
id = 141;
name = "abcd";
duration = "1 year"
})
})
})
})
How can i sort above array using key "type2->properties->payment"?
-------update-----------
I modified the array and used NSSortDescriptor which solved my problem
Upvotes: 1
Views: 3275
Reputation: 1807
Try this by inputing the fares array into this method-
+(NSArray*)sortedListBySize:(NSArray*)_unsortedList{
NSArray *sortedListBySize = [_unsortedList sortedArrayUsingComparator:(NSComparator)^(id obj1, id obj2){
if ([[obj1 valueForKeyPath:@"type2.properties.payments" ] intValue] < [[obj1 valueForKeyPath:@"type2.properties.payments"] intValue]) {
return NSOrderedAscending;
} else if ([[obj1 valueForKeyPath:@"type2.properties.payments" ] intValue] > [[obj1 valueForKeyPath:@"type2.properties.payments"] intValue]) {
return NSOrderedDescending;
}
return NSOrderedSame;
}];
return sortedListBySize;
}
Upvotes: 0
Reputation: 2438
Try this:
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"type1.size" ascending:YES];
NSArray *finalArray = [self.firstArray sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
Upvotes: 2