objective c - Sorting two NSArrays together side by side -
i have several arrays need sorted side side.
for example, first array has names: @[@"joe", @"anna", @"michael", @"kim"]
, , and other array holds addresses: @[@"hollywood bld", @"some street 3", @"that other street", @"country road"]
, arrays' indexes go together. "joe" lives @ "hollywood bld" , on.
i sort names array alphabetically, , have address array sorted alongside still go together, "hollywood bld" having same index "joe". know how sort 1 array alphabetical
nssortdescriptor *sort=[nssortdescriptor sortdescriptorwithkey:@"name" ascending:no]; [myarray sortusingdescriptors:[nsarray arraywithobject:sort]];
but there easy way of getting second array sorted using appropriate order?
- create permutation array, set
p[i]=i
- sort permutation according
name
key of first array - use permutation re-order both arrays
example: let's first array {"quick", "brown", "fox"}
. permutation starts {0, 1, 2}
, , becomes {1, 2, 0}
after sort. can go through permutation array, , re-order original array , second array needed.
nsarray *first = [nsarray arraywithobjects: @"quick", @"brown", @"fox", @"jumps", nil]; nsarray *second = [nsarray arraywithobjects: @"jack", @"loves", @"my", @"sphinx", nil]; nsmutablearray *p = [nsmutablearray arraywithcapacity:first.count]; (nsuinteger = 0 ; != first.count ; i++) { [p addobject:[nsnumber numberwithinteger:i]]; } [p sortwithoptions:0 usingcomparator:^nscomparisonresult(id obj1, id obj2) { // modify use [first objectatindex:[obj1 intvalue]].name property nsstring *lhs = [first objectatindex:[obj1 intvalue]]; // same goes next line: use name nsstring *rhs = [first objectatindex:[obj2 intvalue]]; return [lhs compare:rhs]; }]; nsmutablearray *sortedfirst = [nsmutablearray arraywithcapacity:first.count]; nsmutablearray *sortedsecond = [nsmutablearray arraywithcapacity:first.count]; [p enumerateobjectsusingblock:^(id obj, nsuinteger idx, bool *stop) { nsuinteger pos = [obj intvalue]; [sortedfirst addobject:[first objectatindex:pos]]; [sortedsecond addobject:[second objectatindex:pos]]; }]; nslog(@"%@", sortedfirst); nslog(@"%@", sortedsecond);
Comments
Post a Comment