Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array of dictionaries according to separate array ?

I have a bit of a strange problem. So I have an array of dictionaries say,

(
Dict 1:
"Name" = "B"
"Number" = "2"

Dict 2:
"Name" = "A"
"Number" = "1"

Dict 3:
"Name" = "D"
"Number" = "4"

Dict 4:
"Name" = "C"
"Number" = "3"

Dict 5
"Name" = "E"
"Number" = "5"
)

And say I have an array:

(
"1"
"4"
"2"
)

How can I get an array that contains all the dictionaries that their "Number" key match each object in that array and have it sorted according to the second array?

e.g. output would be

(
Dict 1:
"Name" = "A"
"Number" = "1"

Dict 2:
"Name" = "D"
"Number" = "4"

Dict 3:
"Name" = "B"
"Number" = "2"
)

I think I can use sortedArrayUsingDescriptors but I'm not sure how to specify multiple descriptors. Can the descriptors contain every object in the array? Any help or guidance is much appreciated.

like image 363
Milo Avatar asked Feb 02 '26 14:02

Milo


2 Answers

This has nothing to do with sorting - especially since not every dictionary in the array is even involved. What you want to do is extract each dictionary from the array.

This would be a lot simpler if you didn't have an array of dictionaries at all. Instead, you should start with one big dictionary where the key is the number and the value is whatever (perhaps the whole dictionary, perhaps the name alone). Now you can just look up each number as the key into that dictionary and grab the name.

{ 1 => A, 2 => B, 3 => C ...}

Now just grab objectForKey:@1, objectForKey:@4, objectForKey:@2 and you're done.

like image 139
matt Avatar answered Feb 05 '26 08:02

matt


for (NSNumber *aNumber in testArray) {
    for (NSDictionary *aDict in anArray) {
        if (aNumber.intValue == [(NSNumber *)[aDict valueForKey:@"Number"]intValue]) {
            [finalArray addObject:aDict];
        }
    }
}
like image 37
A_G Avatar answered Feb 05 '26 07:02

A_G



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!