How to Sort Nsmutablearray of Date Objects

How to sort NSMutableArray of date objects

First you should convert all date Strings (which is NSString) objects to NSDate objects and then sort these dateObjects.

I believe you have dateArray containing all those strings.

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"self" 
ascending:NO];
NSArray *descriptors = [NSArray arrayWithObject:descriptor];
NSArray *reverseOrder = [dateArray sortedArrayUsingDescriptors:descriptors];

OR

NSArray *reverseOrderUsingComparator = [dateArray sortedArrayUsingComparator: 
^(id obj1, id obj2) {
return [obj2 compare:obj1];
}];

Sort NSArray of date strings or objects

Store the dates as NSDate objects in an NS(Mutable)Array, then use -[NSArray sortedArrayUsingSelector: or -[NSMutableArray sortUsingSelector:] and pass @selector(compare:) as the parameter. The -[NSDate compare:] method will order dates in ascending order for you. This is simpler than creating an NSSortDescriptor, and much simpler than writing your own comparison function. (NSDate objects know how to compare themselves to each other at least as efficiently as we could hope to accomplish with custom code.)

Sorting NSMutableArray by date

First collect the indices of all objetcs without a birthday.

NSIndexSet *indexSet = [NSIndexSet indexSet];
[array enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL *stop)
{
if(![[dict allKeys] containsObject:@"birthday"]){
[indexSet addIndex:idx];
}
}];

Now remove them from the original array

[array removeObjectsAtIndexes:indexSet];

Using a comparator block, sorting could look like

[array sortUsingComparator: ^(NSDictionary *d1, NSDictionary *d2) {    
NSDate *date1 = [d1 objectForKey:@"birthday"];
NSDate *date2 = [d2 objectForKey:@"birthday"];

return [date1 compare:date2]
}

how to sort the time in a NSMutableArray in ios

It is best to use the sorting methods that are already provided in NSArray. Something like this should do:

NSArray *stortedArray = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *_Nonnull obj1, NSDictionary *_Nonnull obj2) {
return [obj1[@"StartTime"] compare:obj2[@"StartTime"]];
}];

Or if the StartTime is still a string:

NSArray *stortedArray = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *_Nonnull obj1, NSDictionary *_Nonnull obj2) {
return [[dateFormatter dateFromString:obj1[@"StartTime"]] compare:[dateFormatter dateFromString:obj2[@"StartTime"]]];
}];

To change the ascending/descending order you simply swap the obj1 and obj2 when used in the block:

return [obj2[@"StartTime"] compare:obj1[@"StartTime"]];

How to sort an array containing NSDates

Use below code:

  [your array sortUsingComparator:
^NSComparisonResult(id obj1, id obj2){

obj1 *o1 = (obj1*)obj1;
obj2 *o2 = (obj2*)obj2;
if (o1.personAge > 02.personAge) {
return (NSComparisonResult)NSOrderedDescending;
}

return (NSComparisonResult)NSOrderedSame;
}

];

Sort NSMutableArray by date and then by alphabetical order

The method sortUsingDescriptors takes array of NSSortDescriptor as an argument. So you can pass multiple sort descriptors to method as follow:

NSSortDescriptor *sortAlphabetical = [NSSortDescriptor sortDescriptorWithKey:@"title" ascending:YES];
NSSortDescriptor *sortByDate = [NSSortDescriptor sortDescriptorWithKey:@"ActualDate" ascending:YES];
NSArray *sortDescriptors = @[sortAlphabetical, sortByDate];
//perform sorting
[a sortUsingDescriptors:sortDescriptors];

How to sort an array of objects by multiple date fields?

You need to sort based on

  • whether date1 exists
  • then based on date1 value
  • then based on date2 value

Since the dates are in ISO format, you can do string comparison to sort

const input=[{id:"1",date1:"2022-03-21T18:59:36.641Z",date2:"2022-03-17T18:59:36.641Z",},{id:"2",date1:"2022-03-20T18:59:36.641Z",date2:"2022-03-17T18:59:36.641Z",},{id:"3",date2:"2022-03-17T18:59:36.641Z",},{id:"4",date2:"2022-03-15T18:59:36.641Z",}];

input.sort((a,b) =>
( ('date1' in b) - ('date1' in a) )
|| (a.date1 ?? '').localeCompare(b.date1 ?? '')
|| a.date2.localeCompare(b.date2)
)

console.log(input)

How to Sort an array with dates (Type 'string' is not assignable to type 'Date'.)

Convert all the dates from you array to Date objects

// rename your array to avoid conflict with the native Date object
const dates: string[] = ['April 1, 2017 10:39 PM', 'April 1, 2017 10:39 PM', 'January 1, 2018 9:39 PM', 'February 11, 2019 9:39 PM', 'April 1, 2019 10:39 PM']

const sDates = Utils.sDates(
dates.map((date) => new Date(date)),
false
);

console.log(sDates)

Sort array of objects using multiple date properties

By looking at the js sort documentation you'll see that sort is taking a function as parameter which :

  • Return a positive integer if the first object is bigger than the second one
  • Return 0 if the two objects are the same
  • Return a negative integer if the first object is smaller than the second one.

Knowing that, let's build the function together :

First, we'd like to get the highest date for on object.

For that, i would recommend using Math.max which takes an array and returns the biggest parameters.

Here it works because js understand date as integers.

function highestDate(obj){
return Math.max(obj.timestamp1,obj.timestamp2,obj.timestamp3)
}

Now let's build the sort function.

function compare(a,b){
return highestDate(b) - highestDate(a)
}

here is a snipper for testing :

function highestDate(obj){
return Math.max(obj.timestamp1,obj.timestamp2,obj.timestamp3)
}

function compare(a,b){
return highestDate(b) - highestDate(a)
}

let obj1={
id:1,
timestamp1 : new Date(2001,1,1),
timestamp2 : new Date(2002,1,1),
timestamp3 : new Date(2003,1,1) //third highest date
}

let obj2={
id:2,
timestamp1 : new Date(1997,1,1),
timestamp2 : new Date(2004,1,1),//second highest date
timestamp3 : new Date(2003,1,1)
}

let obj3={
id:3,
timestamp1 : new Date(1991,1,1),
timestamp2 : new Date(2001,1,1),
timestamp3 : new Date(2005,1,1) //highest date
}

let arr = [obj1,obj2,obj3]

console.log(arr.sort(compare))


Related Topics



Leave a reply



Submit