How To Sort Date Object In Array?
I want to sort array of objects.I have dates in my object I want to sort the dates of objects I used this answer to solve my problem why array is not sorted in javascript in increa
Solution 1:
The function works fine if you are expecting all dates. Looking at your data there are some invalid dates like "-"
If you can't modify the data or expect a definite date always then you need to mod your function to do something like this (or handle it in some way to your liking)
functionsort_by(field, reverse, primer) {
var key = primer ?
function (x) {
returnprimer(x[field])
} :
function (x) {
return x[field]
};
reverse = !reverse ? 1 : -1;
returnfunction (a, b) {
a = newDate(key(a))=='Invalid Date'?0:newDate(key(a));
b = newDate(key(b))=='Invalid Date'?0:newDate(key(b));
return reverse * (a-b);
}
}
https://jsfiddle.net/rxaLutgn/21/ <-- take a look here an plug in the objects that are badly sorted to limit the amount of data
Solution 2:
Here is a working solution, I did not include the primer like you did. But implementing it should be easy.
$.ajax({
url: "https://dl.dropboxusercontent.com/s/3v7ya481187k8gf/a.json?dl=0",
}).done(function(data) {
var arr;
var _key = "Expected_Payment_Date__c";//"akritiv__Promise_Date__c",var _reverse = true;
arr=JSON.parse(data);
arr.sort(function(a,b){
var keyA = Date.parse(a[_key]);
var keyB = Date.parse(b[_key]);
var _rev = _reverse ? -1 : 1;
if(keyA < keyB) return _rev * -1;
if(keyA > keyB) return _rev * 1;
return0;
});
console.log(arr);
});
Post a Comment for "How To Sort Date Object In Array?"