1

I am getting JSON like below:

"Array1": 
[
  {
    "abc": "3_name",
    "id": 34,
    "order": [3]
  },
  {
    "abc": "1_name",
    "id": 50,
    "order": [1]
  },
  {
    "abc": "2_name",
    "id": 4,
    "order": [2]
  }
]

I don't know how to sort the Array1 according to "order" which is itself an array. Please help. I could not figure out how to sort it using NSSortDescriptor or any other method available in Objective-C.

2
  • Update your question with your attempts to sort this array. Commented May 31, 2016 at 22:10
  • @iOSDeveloper Did you get it to work using my answer? Commented Jun 6, 2016 at 13:53

1 Answer 1

1

You'de want to sort using a comparator, which would look something like:

id customCompare = ^(NSMutableDictionary * obj1, NSMutableDictionary * obj2) {
    return [obj1[@"order"][0] compare:obj2[@"order"][0]];
};

NSArray *sortedArray = [jsonData[@"Array1"] sortedArrayUsingComparator:customCompare];

Where jsonData should be replaced by the correct name of the dict holding the Array1.

Sign up to request clarification or add additional context in comments.

4 Comments

You neglected to mention that this compare: method needs to exist for the objects in array1, not in the class calling sortedArrayUsingSelector:. And this doesn't take into account that you are sorting an array of dictionaries and the sort order is on a further array in those dictionaries.
@maddy changed to local comparator for clarity
It's still completely wrong. sortedArrayUsingSelector: doesn't take a block as an argument. And the implementation of the block doesn't reflect the data being sorted.
@rmaddy Ah, nice catch. Updated the example to exactly match question data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.