I started with this question: How to sort a JS object of objects?
From 2 of the comments I came up with my best way to sort a Javascript object of objects ( just a 2D object ).
Assuming the data
is a 2D object variable, I sort by the customer
value of the inner object.
First I convert to an array of objects, like this:
data = $.map(data, function(k, v) {
return [k];
});
Then I do the sorting like this:
data = data.sort(function(a, b){
return a.customer > b.customer? 1: -1;
});
It works well, but now I want to first sort by a date variable, then secondarily by the customer variable. Just like the way the sorting functions work in SQL (...sort by date desc, customer asc;
).
But, really what I want to do is actually much simpler. When sorting the date values, all I want to do is differentiate between null
and !null
values. The result would be that all the null values would be grouped together, and all the not null values together.
After that, all the top-level objects should be in customer
order.
I came up with this idea, based on how I think it should work:
data = data.sort(function(a, b){
if (a.fin_date !== null){
return 1;
}
return a.customer > b.customer? 1: -1;
});
It is kind-of working. It sorts all the null
values to beginning, and all the null values are in correct alphabetical order, but all the other fin_date
values (!null1
) are not in alphabetical order. They are not in order according to fin_date
either. The objects with fin_date
not equal to null
don't appear to be in any particular order.
So that is my problem: I need the objects with fin-date
!= null
to be in alphabetical order.
Thanks!