why array is not sorted in javascript in increasing date or decreasing date?

后端 未结 2 1603
Happy的楠姐
Happy的楠姐 2021-01-22 09:21

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

2条回答
  •  一个人的身影
    2021-01-22 09:46

    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

提交回复
热议问题