Order Two Nsmutablearrays Based on One

Order two NSMutableArrays based on one

I would put the two arrays into a dictionary as keys and values. Then you can sort the first array (acting as keys in the dictionary) and quickly access the dictionary's values in the same order. Note that this will only work if the objects in the first array support NSCopying because that's how NSDictionary works.

The following code should do it. It's actually quite short because NSDictionary offers some nice convenience methods.

// Put the two arrays into a dictionary as keys and values
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:secondArray forKeys:firstArray];
// Sort the first array
NSArray *sortedFirstArray = [[dictionary allKeys] sortedArrayUsingSelector:@selector(compare:)];
// Sort the second array based on the sorted first array
NSArray *sortedSecondArray = [dictionary objectsForKeys:sortedFirstArray notFoundMarker:[NSNull null]];

Sort two arrays based on the length of one

You could take the indices, sort them and map the values for both arrays.

var array1 = ['maximilian', 'moritz', 'hans'],    array2 = [5, 1, 2000],    indices = array1.map((_, i) => i);    indices.sort((a, b) => array1[a].length - array1[b].length);
array1 = indices.map(i => array1[i]);array2 = indices.map(i => array2[i]);
console.log(array1);console.log(array2);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Two NSMutableArrays sorted according objects of first one

I think you should introduce a Player Class

@interface Player : NSObject
@property(strong) NSString *name;
@property(strong) NSNumber *points;
@end

Instead of keeping the informations in seperated arrays, you would now have a Player object for each player and keep the point inside. Now put all the players in an array, that you can sort easily.

[players sortUsingComparator: ^(Player *p1, Player *p2){
if (p1.points < p2.points)
return NSOrderedAscending;
else if(p1.points > p2.points)
return NSOrderedDescending
return NSOrderedSame;
}];

ordering array with another array

You need first convert your categoryNames array into dictionary with NSString key and NSNumber int value, the value will be the order in the array

//this is example code, this will be your first array (reference value array)
NSArray * array = @[@"prueba",@"prueba2",@"prueba3"];
//first you need convert this array in NSDictionary

NSMutableDictionary * arrayDict = [NSMutableDictionary dictionary];
int counter = 0;
for (NSString * value in array) {
if(arrayDict[value] == nil)
{
arrayDict[value] = [NSNumber numberWithInt:counter];
}
counter++;
}

After that then you can get the value and order with sortedArrayUsingComparator method, something like this

//this is an example of your second array categoryTempElements
NSArray * arrayOfObjs = @[[testObject testObjectWithName:@"prueba3"],[testObject testObjectWithName:@"prueba"],[testObject testObjectWithName:@"prueba2"]];

NSArray * sorted = [arrayOfObjs sortedArrayUsingComparator:^NSComparisonResult(testObject * _Nonnull obj1, testObject * _Nonnull obj2) {
if([((NSNumber*)arrayDict[obj1.cName]) intValue] < [((NSNumber*)arrayDict[obj2.cName]) intValue]){
return NSOrderedAscending;
}

if([((NSNumber*)arrayDict[obj1.cName]) intValue] > [((NSNumber*)arrayDict[obj2.cName]) intValue]){
return NSOrderedDescending;
}

return NSOrderedSame;
}];

for (testObject * obj in sorted) {
NSLog(@"%@",obj.cName);
}

And voila in sorted you will have your array of object sorted by your first array NSString order

Hope this helps

Sort two arrays the same way

You can sort the existing arrays, or reorganize the data.

Method 1:
To use the existing arrays, you can combine, sort, and separate them:
(Assuming equal length arrays)

var names = ["Bob","Tom","Larry"];
var ages = ["10", "20", "30"];

//1) combine the arrays:
var list = [];
for (var j = 0; j < names.length; j++)
list.push({'name': names[j], 'age': ages[j]});

//2) sort:
list.sort(function(a, b) {
return ((a.name < b.name) ? -1 : ((a.name == b.name) ? 0 : 1));
//Sort could be modified to, for example, sort on the age
// if the name is the same.
});

//3) separate them back out:
for (var k = 0; k < list.length; k++) {
names[k] = list[k].name;
ages[k] = list[k].age;
}

This has the advantage of not relying on string parsing techniques, and could be used on any number of arrays that need to be sorted together.

Method 2: Or you can reorganize the data a bit, and just sort a collection of objects:

var list = [
{name: "Bob", age: 10},
{name: "Tom", age: 20},
{name: "Larry", age: 30}
];

list.sort(function(a, b) {
return ((a.name < b.name) ? -1 : ((a.name == b.name) ? 0 : 1));
});

for (var i = 0; i<list.length; i++) {
alert(list[i].name + ", " + list[i].age);
}

For the comparisons,-1 means lower index, 0 means equal, and 1 means higher index. And it is worth noting that sort() actually changes the underlying array.

Also worth noting, method 2 is more efficient as you do not have to loop through the entire list twice in addition to the sort.

http://jsfiddle.net/ghBn7/38/

Two arrays of objects and need to sort one based on the other

You can achieve this by:

var array1 = [ { "key": 0, "display": "hide", }, { "key": 1, "display": "show", }, { "key": 2, "display": "show", }];var array2 = [ { "key": 1, "question": "some text here", }, { "key": 0, "question": "Different text here", }, { "key": 2, "question": "Even more different", }];
var keys = array2.map(el => el.key);array1.sort((a, b) => keys.indexOf(a.key) - keys.indexOf(b.key));console.log(array1);

Sort two arrays from object depending on one of those arrays in Javascript

For each object, construct a Map whose keys are fruit strings and values are the associated original number in the c array. Sort the c array, then sort the b array based on the difference between the items in the map:

const arr = [   {a: 1, b: ['apple', 'banana', 'orange', 'mango'], c: [42, 7, 18, 5]},   {a: 2, b: ['apple', 'banana', 'orange', 'mango'], c: [4, 101, 88, 3]},   {a: 3, b: ['apple', 'banana', 'orange', 'mango'], c: [14, 10, 5, 12]},   {a: 4, b: ['apple', 'banana', 'orange', 'mango'], c: [99, 2, 105, 101]}];Object.values(arr).forEach(({ b, c }) => {  const fruitValues = c.reduce(    (map, num, i) => map.set(b[i], num),    new Map()  );  c.sort((a, b) => a - b);  b.sort((a, b) => fruitValues.get(a) - fruitValues.get(b));});console.log(arr);

How do I sort an NSMutableArray with custom objects in it?

Compare method

Either you implement a compare-method for your object:

- (NSComparisonResult)compare:(Person *)otherObject {
return [self.birthDate compare:otherObject.birthDate];
}

NSArray *sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(compare:)];

NSSortDescriptor (better)

or usually even better:

NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"birthDate"
ascending:YES];
NSArray *sortedArray = [drinkDetails sortedArrayUsingDescriptors:@[sortDescriptor]];

You can easily sort by multiple keys by adding more than one to the array. Using custom comparator-methods is possible as well. Have a look at the documentation.

Blocks (shiny!)

There's also the possibility of sorting with a block since Mac OS X 10.6 and iOS 4:

NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingComparator:^NSComparisonResult(Person *a, Person *b) {
return [a.birthDate compare:b.birthDate];
}];

Performance

The -compare: and block-based methods will be quite a bit faster, in general, than using NSSortDescriptor as the latter relies on KVC. The primary advantage of the NSSortDescriptor method is that it provides a way to define your sort order using data, rather than code, which makes it easy to e.g. set things up so users can sort an NSTableView by clicking on the header row.

How do I sort an array of arrays containing two values in Objective-C?

NSArray and NSMutableArray offer a number of sorting methods. For your purpose, the easy way would probably be to use -sortUsingComparator: like this:

[_timeSheets sortUsingComparator:^(id obj1, id obj2) {
if ([obj1 objectAtIndex:1] > [obj2 objectAtIndex:1]) {
return (NSComparisonResult)NSOrderedDescending;
}
if ([obj1 objectAtIndex:1] < [obj2 objectAtIndex:1]) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];

The block you supply gets two parameters and returns a NSComparisonResult. Each item in your array is itself an array, so the objects you'll get for obj1 and obj2 are your two-element sub-arrays. The comparison block is applied repeatedly to pairs of objects in the _timeSheets to determine their relative positions.

Note: The comparator block above is based on the example in the NSArray documentation. Look there for more information on sorting.

How to sort two arrays with one being sorted based on the sorting of the other?

Pair Class could do the trick here.

import java.util.*;
public class Main
{
static class Pair implements Comparable<Pair>
{
int a1;
int a2;
Pair (int a1, int a2) //constructor
{
this.a1 = a1;
this.a2 = a2;
}
public int compareTo(Pair other) //making it only compare a2 values
{
return this.a2 - other.a2;
}
}
public static void main(String[] args)
{
int[] A1 = {1,2,3,4,5,6,7,8,9,10};
int[] A2 = {1,2,3,0,2,1,1,0,0,0};
Pair[] pairs = new Pair[A1.length];
for (int i = 0; i < pairs.length; i++)
{
pairs[i] = new Pair(A1[i], A2[i]);
}
Arrays.sort(pairs);
//printing values
for (int i = 0; i < A1.length; i++)
{
System.out.print(pairs[i].a1 + " ");
}
System.out.println();
for (int i = 0; i < A2.length; i++)
{
System.out.print(pairs[i].a2 + " ");
}
}
}

By making a Pair class that holds 2 variables a1 and a2, you can override the compareTo method to only compare the a2 value, so that when Arrays.sort is called, the pairs in the Pair array will be swapped only according to the a2 values. You can then access the values in the pairs and print them out. This will produce your desired output.



Related Topics



Leave a reply



Submit