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

后端 未结 2 1602
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

    0 讨论(0)
  • 2021-01-22 10:00

    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

    0 讨论(0)
提交回复
热议问题