I have an array populated by dictionaries, and I need to sort the array alphabetically by the values of one of the keys of the dictionaries.
This is my array:
tu dictus: ( { brand = Ryul; productTitle = Any; quantity = 1; subBrand = "Ryul INJ"; type = Product; }, { brand = Trol; productTitle = Different; quantity = 2; subBrand = ""; type = Brand; }, { brand = Dtor; productTitle = Any; quantity = 1; subBrand = ""; type = Product; }, { brand = Ryul; productTitle = Different; quantity = 2; subBrand = "Ryul CHES"; type = SubBrand; }, { brand = Anan; productTitle = Any; quantity = 1; subBrand = ""; type = Product; } )
Normally for sorting an array I will use
myArray = [uniqueProdsArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
But how do sort using the brand
key of the dictionary?
To sort a list of dictionaries according to the value of the specific key, specify the key parameter of the sort() method or the sorted() function. By specifying a function to be applied to each element of the list, it is sorted according to the result of that function.
To sort a dictionary by value in Python you can use the sorted() function. Python's sorted() function can be used to sort dictionaries by key, which allows for a custom sorting method. sorted() takes three arguments: object, key, and reverse. Dictionaries are unordered data structures.
Swift Dictionary sorted()The sorted() method sorts a dictionary by key or value in a specific order (ascending or descending).
I think this will do it:
brandDescriptor = [[NSSortDescriptor alloc] initWithKey:@"brand" ascending:YES]; sortDescriptors = [NSArray arrayWithObject:brandDescriptor]; sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors];
I pulled the code from Sort Descriptor Programming Topics. Also, Key-Value Coding comes into play, in that sortedArrayUsingDescriptors:
will send a valueForKey:
to each element in myArray
, and then use standard comparators to sort the returned values.
We Got The Solution By Using The Method Follows
[self.jsonData sortUsingDescriptors: [NSArray arrayWithObjects: [NSSortDescriptor sortDescriptorWithKey:"fullname" ascending:YES], [NSSortDescriptor sortDescriptorWithKey:"id" ascending:NO], nil]];
Where:-
jsonData
- MutableArray Which holds the Parsed JSON Data.
fullname
- the data we want to sort.
id
- An unique data which comes with the inner dictionary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With