SORTING NSArray of NSDICTIONARIES by value of a key

One of most common question is how to sort an array with dictionaries by value of a key. NSSortDescriptor is useful to answer this question. For example;

You have a JSON array like this:

[
	{
		color: "red",
		value: "#f00"
	},
	{
		color: "green",
		value: "#0f0"
	},
	{
		color: "blue",
		value: "#00f"
	},
	{
		color: "cyan",
		value: "#0ff"
	},
	{
		color: "magenta",
		value: "#f0f"
	},
	{
		color: "yellow",
		value: "#ff0"
	},
	{
		color: "black",
		value: "#000"
	}
]

If we need to sort this array according to value of “color” key. All you need to use NSSortDescriptor. Let my array’s name is “myArray”;

NSSortDescriptor * sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"color" ascending:YES];
NSArray * sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray * sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors];

Nice days
Keep coding…

Leave a comment