3
votes

I have an array of products classes. Each product class has multiple properties such as name, functions, ingredients, etc.

I developed a simple search algorithm using NSPredicate that allows me to search for a specific string in the array of products.

In a nutshell, the predicate looks like: "string in product.name OR string in product.ingredients OR string in product.functions...".

I can get the result array correctly, i.e. list of products that contains the search string in one of its properties.

BUT, my question is, how to sort this result by RELEVANCE? i.e. if a search string hits multiple times in a product class, naturally I want to put this product at the top of the search result array?

Thanks!

1

1 Answers

0
votes

I have coded an example that might answer your question. I am not saying this is the best implementation, but it works.

NSArray *strings = @[@"A",@"B",@"C",@"A",@"D",@"E",@"B",@"B",@"B"];

NSMutableDictionary *sortedDictionary = [NSMutableDictionary dictionary];
for (NSString *string in strings) {
    NSNumber *count = [sortedDictionary objectForKey:string];
    if (count) {
        count = @(count.integerValue + 1);
    } else {
        count = @(1);
    }
    [sortedDictionary setObject:count forKey:string];
}

NSArray *result = [sortedDictionary keysSortedByValueWithOptions:NSNumericSearch usingComparator:^NSComparisonResult(id obj1, id obj2) {
    return [obj2 compare:obj1];
}];
NSLog(@"%@", result); // (B,A,D,E,C)