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

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

提交回复
热议问题