1

I have a NSArray of NSDictionary. I have two specific keys which I want to use to sort my array. Basically, I currently have two NSSortDescriptors:

descriptor = [NSSortDescriptor sortDescriptorWithKey:@"averageNote" ascending:NO];
descriptor2 = [NSSortDescriptor sortDescriptorWithKey:@"reviews.@count" ascending:NO];

They simply sort my array based on the average note of its elements, and then in the second place based on the number of reviews.

I would like to combine these two elements to make a more realistic ranking: for instance, 70% average note and 30% review count.

How can I achieve this?

Alladinian
  • 34,483
  • 6
  • 89
  • 91
el-flor
  • 1,466
  • 3
  • 18
  • 39
  • Check out this question: http://stackoverflow.com/questions/805547/how-to-sort-an-nsmutablearray-with-custom-objects-in-it. You can sort the array using a block and could multiply the average and count values by the percentages you described above and compare the result. – Patrick Goley Mar 20 '17 at 14:02
  • Great, thanks a lot. – el-flor Mar 20 '17 at 14:26
  • Another way to accomplish this, is to add a computed property say `rank` and use this for sorting. – Amin Negm-Awad Mar 20 '17 at 17:48

1 Answers1

0

this code will let the array sort itself by the rank you want,and the array will be sorted ascending ,if you want it by descending,change NSOrderedAscending to NSOrderedDescending.

NSMutableArray *array = [@[] mutableCopy];
[array sortedArrayWithOptions:NSSortStable usingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
    aClass a = obj1;
    aClass b = obj2;
    float rankOfA = a.averageNote*0.7 + a.reviewCount*0.3;
    float rankOfB = b.averageNote*0.7 + b.reviewCount*0.3;
    if (rankOfA > rankOfB) {
        return NSOrderedAscending;
    }
}];
Henson Fang
  • 1,177
  • 7
  • 30