如何在 Javascript ES6 中按年和月排序

How to sort by Year and Month in Javascript ES6

我有一个这样组织的数组。

const array = [
  {
    Year: 2018,
    Month: 'Dec'
  },
  {
    Year: 2017,
    Month: 'Apr'
  },
  {
    Year: 2018,
    Month: 'Mar'
  },
  {
    Year: 2018,
    Month: 'Oct'
  },
  {
    Year: 2017,
    Month: 'Jan'
  },
  {
    Year: 2018,
    Month: 'Apr'
  }
]

我已经成功地按年或按月组织了数据,但每次我尝试同时按它们组织数据时,最后组织数据的那个将取代之前的所有数据。我明白它为什么这样做,但似乎找不到解决方法。

const sortedByYear = array.sort((a, b) => a.Year - b.Year);

按年份排序非常简单。

const sorted = sortedByYear.sort((a, b) => Months.indexOf(a.Month) - Months.indexOf(b.Month));

按月排序。

我尝试在月份检查器中添加某种检查器,如果年份匹配则求助,但这并没有解决排序方式的问题。

您必须在 sort 函数中放置 both 个测试:

const input = [
  {
    Year: 2018,
    Month: 'Dec'
  },
  {
    Year: 2017,
    Month: 'Apr'
  },
  {
    Year: 2018,
    Month: 'Mar'
  },
  {
    Year: 2018,
    Month: 'Oct'
  },
  {
    Year: 2017,
    Month: 'Jan'
  },
  {
    Year: 2018,
    Month: 'Apr'
  }
];
const Months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
input.sort((a, b) => {
  if (a.Year !== b.Year) return a.Year - b.Year;
  return Months.indexOf(a.Month) - Months.indexOf(b.Month)
});
console.log(input);

您可以使用 lodash sortBy 并将要排序依据的字段作为数组传递。

const sorted = _.sortBy(array, ['Year', 'Month']);

您可以使用 yearmonth 的组合来形成比较标准。 padStart 无法在 IE 上运行,因此您可能需要一个 polyfill。

const input = [
  {
    Year: 2018,
    Month: 'Dec'
  },
  {
    Year: 2017,
    Month: 'Apr'
  },
  {
    Year: 2018,
    Month: 'Mar'
  },
  {
    Year: 2018,
    Month: 'Oct'
  },
  {
    Year: 2017,
    Month: 'Jan'
  },
  {
    Year: 2018,
    Month: 'Apr'
  }
];
const Months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
input.sort((a, b) =>`${a.Year}${Months.indexOf(a.Month).toString().padStart(2,0)}` - `${b.Year}${Months.indexOf(b.Month).toString().padStart(2,0)}`
);
console.log(input);