javascript 按月对对象数组排序

qacovj5a  于 2023-01-04  发布在  Java
关注(0)|答案(4)|浏览(170)

我正在使用 Jmeter 板,我有一个图表,我必须在其中显示计数对月份标签。我有一个对象与计数和月份键数组。我想排序这个对象数组在升序与月份键值。我尝试下面的代码在chrome工作正常,但数组在Firefox中没有得到排序。

var xAxis =  [
{count: 0, month: "Jan 2019"},
{count: 7, month: "Dec 2019"},
{count: 0, month: "Feb 2019"},
{count: 0, month: "Jul 2019"}
] 

 xAxis.sort(function(a, b) {
  var c = new Date(a.month);
  console.log("TCL: CountByUserGraph -> makeApiCall -> c", c)
  // Chrome showing  ==> Tue Jan 01 2019 00:00:00 GMT+0530 
  //firefox showing  ==> Invalid Date
  var d = new Date(b.month);
  return c - d;
});
zphenhs4

zphenhs41#

你可以创建一个包含所有月份短名称的数组,然后,拆分输入中的字符串,得到月份的短名称,并将其与数组中的项进行比较。

var months = ['Jan', 'Feb', 'Mar', 'Apr', 
              'May', 'June', 'Jul', 'Aug', 
              'Sept', 'Oct', 'Nov', 'Dec'];

var xAxis =  [
{count: 0, month: "Jan 2019"},
{count: 7, month: "Dec 2019"},
{count: 0, month: "Feb 2019"},
{count: 0, month: "Jul 2019"}
];

var output = xAxis.sort(function (a, b) { 
    return months.indexOf(a.month.substr(0, 3)) - months.indexOf(b.month.substr(0, 3)) 
});

console.log(output);
ipakzgxi

ipakzgxi2#

以下实现比较了年和月-

const sortByMonth = arr => {
  const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  const getIndexOfMonth = month => months.indexOf(month)
  return [ ...arr ].sort((left, right) => {
    const [ leftMonth, leftYear ] = left.month.split(' ')
    const [ rightMonth, rightYear ] = right.month.split(' ')
    if (leftYear !== rightYear) {
      return parseInt(leftYear) - parseInt(rightYear)
    }
    return getIndexOfMonth(leftMonth) - getIndexOfMonth(rightMonth)
  })
}

var xAxis =  [
  {count: 0, month: "Jan 2019"},
  {count: 7, month: "Dec 2019"},
  {count: 0, month: "Dec 2017"},
  {count: 0, month: "Jun 2018"},
  {count: 0, month: "Feb 2019"},
  {count: 0, month: "Jul 2019"},
];

console.log(sortByMonth(xAxis))
c9qzyr3d

c9qzyr3d3#

Firefox的Date实现无法解析MMM YYYY的字符串(如示例中的字符串)。请考虑使用其他格式。如果必须使用此格式,请考虑使用允许您跨Momentjsdate-fns等浏览器解析这些日期的库。

hfyxw5xn

hfyxw5xn4#

你打错了。我给你看:

var xAxis =  [
{count: 0, month: "Jan 2019"},
{count: 7, month: "Dec 2019"},
{count: 0, month: "Feb 2019"},
{count: 0, month: "Jul 2019"}
] 

 xAxis.sort(function(a, b) {
  var c = new Date(a.month);
  // console.log("TCL: CountByUserGraph -> makeApiCall -> c", c)
  // Chrome showing  ==> Tue Jan 01 2019 00:00:00 GMT+0530 
  //firefox showing  ==> Invalid Date
  var d = new Date(b.month);
  return c - d;
});

console.log(xAxis);

排印错误行为var d = ...。您将两个日期都设置为a
[编辑]请注意:我在上面贴出的代码可以在Chrome上运行,但是一位用户 Alexandria 在下面贴出了同样的代码并不能在所有浏览器上运行。

相关问题