Sorting Nil Dates to the End of an Array

Sorting nil Dates to the end of an Array

Maybe not the cleanest solution, but you can do it in one step with nil-coalescing.

objectArray.sort{ ($0.date ?? .distantPast) > ($1.date ?? .distantPast) }

How to sort array by date when some dates are null

Transform the strings to dates and sort. For the nulls, use date in the distant future so they will sort to the end.

let dates = [  { due_date: null },  { due_date: '03/11/2020' },  { due_date: '02/10/2020' }]
const distantFuture = new Date(8640000000000000)const firstSort = 'due_date'
let sorted = dates.sort((a, b) => { let dateA = a[firstSort] ? new Date(a[firstSort]) : distantFuture let dateB = b[firstSort] ? new Date(b[firstSort]) : distantFuture return dateA.getTime() - dateB.getTime()})
console.log(sorted)

javascript sorting array of object according to date in string with some null values

Check the validity of date object and run the code return the value I have done a similar thing below for you

var array = [{
"_id": "5f6a0c223932cd1f7ae1d48c",
"user_id": "5e82f6d1ca6f2a3b4d2212a1",
"current_term_renewal_date": "Fri Oct 16 2020 00:00:00"
},
{
"_id": "5f6990b94130056cd6034091",
"user_id": "5e82f6d1ca6f2a3b4d2212a1",
"current_term_renewal_date": ""

},
{
"_id": "5f6a0c2a3932cd1f7ae1d48d",
"user_id": "5e82f6d1ca6f2a3b4d2212a1",
"current_term_renewal_date": "Fri Nov 27 2020 00:00:00"

},

{
"_id": "5f6a0c453932cd1f7ae1d48e",
"user_id": "5e82f6d1ca6f2a3b4d2212a1",
"current_term_renewal_date": "Thu Oct 22 2020 00:00:00"
},

{
"_id": "5f6a0c4d3932cd1f7ae1d48f",
"user_id": "5e82f6d1ca6f2a3b4d2212a1",
"current_term_renewal_date": "Thu Nov 19 2020 00:00:00"

},

{
"_id": "5f6a0c5a3932cd1f7ae1d490",
"user_id": "5e82f6d1ca6f2a3b4d2212a1",
"current_term_renewal_date": "Thu Dec 03 2020 00:00:00"

},

{
"_id": "5f1bd948a1db382540356394",
"user_id": "5e82f6d1ca6f2a3b4d2212a1",
"current_term_renewal_date": "Mon Jul 13 2020 20:30:00"

},
{
"_id": "5f698ca54130056cd603408e",
"user_id": "5e82f6d1ca6f2a3b4d2212a1",
"current_term_renewal_date": "Fri Sep 25 2020 00:00:00"

},
{
"_id": "5f698cae4130056cd603408f",
"user_id": "5e82f6d1ca6f2a3b4d2212a1",
"current_term_renewal_date": "Thu Sep 24 2020 00:00:00"

},
{
"_id": "5f698cb64130056cd6034090",
"user_id": "5e82f6d1ca6f2a3b4d2212a1",
"current_term_renewal_date": "Wed Sep 23 2020 00:00:00"

},

{
"_id": "5f6a0c163932cd1f7ae1d48b",
"user_id": "5e82f6d1ca6f2a3b4d2212a1",
"current_term_renewal_date": "Sun Nov 08 2020 00:00:00"

}
]
array.sort(function compare(a, b) {
var dateA = new Date(a.current_term_renewal_date);
var dateB = new Date(b.current_term_renewal_date);
if (!dateA.toJSON()) {
return 1;
}
if (!dateB.toJSON()) {
return -1;
}
return dateA - dateB;
});
console.log("result", array)

Sort nil to the end of an array of optional strings

You can provide a custom comparator which considers nil
as larger than any non-nil value:

let array = ["b", nil, "a", nil]

let sortedArray = array.sorted { (lhs, rhs) -> Bool in
switch (lhs, rhs) {
case let(l?, r?): return l < r // Both lhs and rhs are not nil
case (nil, _): return false // Lhs is nil
case (_?, nil): return true // Lhs is not nil, rhs is nil
}
}

print(sortedArray) // [Optional("a"), Optional("b"), nil, nil]

This works with any array of optional comparable elements, and avoids
the usage of “magical large” values. The comparator can be implemented
as a generic function:

func compareOptionalsWithLargeNil<T: Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let(l?, r?): return l < r // Both lhs and rhs are not nil
case (nil, _): return false // Lhs is nil
case (_?, nil): return true // Lhs is not nil, rhs is nil
}
}

print(["b", nil, "a", nil].sorted(by: compareOptionalsWithLargeNil))
// [Optional("a"), Optional("b"), nil, nil]

print([2, nil, 1].sorted(by: compareOptionalsWithLargeNil))
// [Optional(1), Optional(2), nil]

print([3.0, nil, 1.0].sorted(by: compareOptionalsWithLargeNil))
// [Optional(1.0), Optional(3.0), nil]

print([Date(), nil, .distantPast, nil, .distantFuture].sorted(by: compareOptionalsWithLargeNil))
// [Optional(0000-12-30 00:00:00 +0000), Optional(2018-11-22 13:56:03 +0000),
// Optional(4001-01-01 00:00:00 +0000), nil, nil]

Sort an array so that null values always come last

Check out .sort() and do it with custom sorting.
Example

function alphabetically(ascending) {
return function (a, b) {
// equal items sort equally
if (a === b) {
return 0;
}

// nulls sort after anything else
if (a === null) {
return 1;
}
if (b === null) {
return -1;
}

// otherwise, if we're ascending, lowest sorts first
if (ascending) {
return a < b ? -1 : 1;
}

// if descending, highest sorts first
return a < b ? 1 : -1;
};
}

var arr = [null, "a", "z", null, "b"];

console.log(arr.sort(alphabetically(true)));
console.log(arr.sort(alphabetically(false)));

Problem sorting an array of objects by date & time in Javascript - null values allowed

You can simplify the sorting algorithm by a great deal if you pre-process your array so that it will have a numeric representation of the column you want to sort by.

Add a column to the table that contains the UTC equivalent of the dates for instance. Then you can safely sort the array by the UTC property, but you will still display the string value.

for (var idx in _places)
_places[idx].UTC = _places[idx].date ? new Date(_places[idx].date).UTC() : 0;

_places.sort(function(a, b)
{
return a.UTC > b.UTC ? 1 : a.UTC < b.UTC ? -1 : 0;
});

If you don't want to use the Date object (pre-1970 dates):

for (var idx in _places)
{
var row = _places[idx];
if (!row.date)
{
row.sortable = 0;
continue;
}
var date = row.date.split('/');
row.sortable = 10000 * parseInt(date[2]) + 100 * parseInt(date[0]) + parseInt(date[1]); // year, month, day
}

_places.sort(function(a, b)
{
return a.sortable > b.sortable ? 1 : a.sortable < b.sortable ? -1 : 0;
});

Of course this assumes that your dates will always have the same M/D/Y format.

Here's the above algorithm in action: http://jsfiddle.net/krNnn/

Sort null values to last in Array of Objects

You could test the value. If null, then take the delta of the comparison.

var c = [{ a: null }, { a: 12 }, { a: 1 }, { a: 50 }, { a: 2 }, { a: null }];
c.sort(function (a, b) { return (a.a === null) - (b.a === null);});
console.log(c);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sort array ascending with zero at the end in Swift

Replace any 0 encountered with a large number like Int.max in the areInIncreasingOrder predicate parameter for sorted:

let score = [3, 0, 4, 6]
let ranking = score.sorted{ ($0 == 0 ? Int.max : $0) < ($1 == 0 ? Int.max : $1) }
print(ranking)

Output:

[3, 4, 6, 0]

Sort an array of numbers so that null values come last

You can first sort by not null and then by numbers.

var arr = [5, 25, null, 1, null, 30]
arr.sort(function(a, b) { return (b != null) - (a != null) || a - b;})
console.log(arr)

sorting a ruby array of objects by an attribute that could be nil

How about in Child defining <=> to be based on category.position if category exists, and sorting items without a category as always greater than those with a category?

class Child
# Not strictly necessary, but will define other comparisons based on <=>
include Comparable
def <=> other
return 0 if !category && !other.category
return 1 if !category
return -1 if !other.category
category.position <=> other.category.position
end
end

Then in Parent you can just call children.sort.



Related Topics



Leave a reply



Submit