首页 > 解决方案 > 基于字符串值的数组排序不起作用

问题描述

我正在尝试Array使用字段对一个String字段进行排序,但它的排序错误。

我的代码看起来像这样。

 let tempWEArray = [
    {
      "from" : "09/2005",
      "to" : "11/2006"
    }, 
    {
      "from" : "09/2006",
      "to" : "11/2007"
    }, 
    {
      "from" : "12/2007",
      "to" : "01/2009"
    }, 
    {
      "from" : "01/2009",
      "to" : "12/2012"
    }, 
    {
      "from" : "01/2013",
      "to" : "03/2018"
    }]

    function sortBy(prop){
        return function(a,b){
            if( a[prop] < b[prop])
            {
                return -1;
            }
            else if( a[prop] > b[prop] )
            {
                return 1;
            }
            return 0;
        }
    }
    
    console.log(tempWEArray.sort(sortBy("to")))

获得的输出如下所示。

0: Object { from: "12/2007", to: "01/2009" }
​
1: Object { from: "01/2013", to: "03/2018" }
​
2: Object { from: "09/2005", to: "11/2006" }
​
3: Object { from: "09/2006", to: "11/2007" }
​
4: Object { from: "01/2009", to: "12/2012" }

如上所示,数组未正确排序。一个字段放错了位置。难道我做错了什么?

以下所有答案都有效,我选择了我已实施的答案。感谢大家。

标签: javascriptnode.js

解决方案


您可以先解析这些日期,然后再-对它们进行排序。

let arr = [{"from":"09/2005","to":"11/2006"},{"from":"09/2006","to":"11/2007"},{"from":"12/2007","to":"01/2009"},{"from":"01/2009","to":"12/2012"},{"from":"01/2013","to":"03/2018"}]

const parse = str => {
  let date = new Date;
  let [month, year] = str.split('/')
  date.setYear(year);
  date.setMonth(+month - 1)
  return date;
}

const sortBy = prop => (a, b) => {
  return parse(b[prop]) - parse(a[prop])
}

arr.sort(sortBy('to'))
console.log(arr)


推荐阅读