I am trying to sort my array of objects .Objects have date property.I need to sort my array in ascending or descending dates .I try like this
https://jsfiddle.net/rxaLu
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)
function sort_by(field, reverse, primer) {
var key = primer ?
function (x) {
return primer(x[field])
} :
function (x) {
return x[field]
};
reverse = !reverse ? 1 : -1;
return function (a, b) {
a = new Date(key(a))=='Invalid Date'?0:new Date(key(a));
b = new Date(key(b))=='Invalid Date'?0:new Date(key(b));
return reverse * (a-b);
}
}
All props to @void for his answer. I just updated since there was a duplicate question raised for this and I don't have rep to comment on the question or on @void's answer on this post
Your function is pretty messed up, try
function sort_by(field, reverse, primer) {
var key = primer ?
function (x) {
return primer(x[field])
} :
function (x) {
return x[field]
};
reverse = !reverse ? 1 : -1;
return function (a, b) {
a = new Date(key(a)), b = new Date(key(b));
return reverse * (a-b);
}
}
You need to convert date strings to date to sort and also you need to change your return code.
Working fiddle