如何按时间对对象数组进行排序?

4

I have an array of object such as

[{
  time: "13:20",
  key2: "",
  key3: ""
}, {
  time: "13:40",
  key2: "",
  key3: ""
}, {
  time: "04:20",
  key2: "",
  key3: ""
}]

我希望它们按时间排序。我研究了momentjs,但没找到有用的东西。

我面临的主要问题是如何将获取到的时间转换为字符串格式,以进行比较排序。任何形式的帮助都将不胜感激。谢谢。


你是否总是有“小时:分钟”格式的字符串? - jo_va
6个回答

3
你可以为所有时间设置相同的日期,然后使用getTime()进行比较。

let arr = [{
  time: "13:20",
  key2: "",
  key3: ""
}, {
  time: "13:40",
  key2: "",
  key3: ""
}, {
  time: "04:20",
  key2: "",
  key3: ""
}]

const toTime = (t) => new Date(`December 17, 1995 ${t}`).getTime();


arr.sort((a,b) => toTime(a.time) - toTime(b.time))

console.log(arr)


2
如果您的时间字符串格式为 HH:MM,则可以使用 String.prototype.localeCompare() 进行字典排序:

const data = [
  { time: '13:20', key2: '', key3: '' },
  { time: '13:40', key2: '', key3: '' },
  { time: '04:20', key2: '', key3: '' },
  { time: '23:03', key2: '', key3: '' }
];

const ascending = [...data].sort((a, b) => a.time.localeCompare(b.time));
const descending = [...data].sort((a, b) => b.time.localeCompare(a.time));

console.log(JSON.stringify(ascending));
console.log(JSON.stringify(descending));

如果您的时间字符串不遵循这种格式,例如可以被指定为 HHHHH:MHH:MM 等等,那么您可以使用 RegExp.prototype.exec() 方法解析该字符串:

const data = [
  { time: '13:20', key2: '', key3: '' },
  { time: '13:40', key2: '', key3: '' },
  { time: '04:20', key2: '', key3: '' },
  { time: ' 4:25', key2: '', key3: '' },
  { time: '23:03', key2: '', key3: '' },
  { time: '14: 3', key2: '', key3: '' },
  { time: ' 2   ', key2: '', key3: '' },
];

const hourMinutes = str => /\s*(?<hh>\d*)\s*:?\s*(?<mm>\d*)\s*/.exec(str);
const toMinutes = ({ hh = 0, mm = 0 }) => (+hh) * 60 + (+mm);
const toTime = ({ time }) => toMinutes(hourMinutes(time).groups);

const ascending = [...data].sort((a, b) => toTime(a) - toTime(b));
const descending = [...data].sort((a, b) => toTime(b) - toTime(a));

console.log(JSON.stringify(ascending));
console.log(JSON.stringify(descending));


这种方法假设时间值将为两位数。如果您将““04:20””更改为““4:20””,则会导致失败。 - Rajesh
@Rajesh,你是对的,这就是为什么我在我的答案中添加了HH:MM的假设,OP时间字符串似乎是按照这种格式进行格式化的。 - jo_va
1
我在比较日期时间值时遇到了很多问题,因此加了一个警告。 - Rajesh
@Rajesh,这是一个非常有价值的观点,我会编辑我的回答!谢谢。 - jo_va

2
你可以采取以下方法进行排序:

逻辑

  • 创建日期对象并添加必要的时间值。
  • 根据这些日期值进行排序。

具有基于日期的方法的好处在于它将处理所有时间值情况。我已更新数据以演示秒值。


将Original Answer翻译成"最初的回答"

var data = [{
  time: "13:20",
  key2: "",
  key3: ""
}, {
  time: "13:40",
  key2: "",
  key3: ""
}, {
  time: "04:20:10",
  key2: "",
  key3: ""
}, {
  time: "04:20:20",
  key2: "",
  key3: ""
}];

function getAddedTimeValue(time) {
  const parts = [...time.split(':'), 0, 0, 0, 0].slice(0, 4);
  const date = new Date();
  date.setHours.apply(date, parts);
  return date.getTime();
}

data.sort((a, b) => getAddedTimeValue(a.time) - getAddedTimeValue(b.time));

// For descending:
// data.sort((a, b) => getAddedTimeValue(b.time) - getAddedTimeValue(a.time));

console.log(data)


1
你可以简单地获取在:之前的第一个数字部分并进行比较排序,如果第一部分相同,则考虑在:之后的第二个数字部分。 升序排列

var arr = [{
  time: "13:20",
  key2: "",
  key3: ""
}, {
  time: "13:40",
  key2: "",
  key3: ""
}, {
  time: "04:20",
  key2: "",
  key3: ""
}];

arr.sort(function(a, b) {
  var aSplit = a.time.split(':');
  var bSplit = b.time.split(':');
  return (aSplit[0] - bSplit[0] || aSplit[1] - bSplit[1]);
});
console.log(arr);

降序排列

var arr = [{
  time: "13:20",
  key2: "",
  key3: ""
}, {
  time: "13:40",
  key2: "",
  key3: ""
}, {
  time: "04:20",
  key2: "",
  key3: ""
}];

arr.sort(function(a, b) {
  var aSplit = a.time.split(':');
  var bSplit = b.time.split(':');
  return (bSplit[0] - aSplit[0] || bSplit[1] - aSplit[1]);
});
console.log(arr);


1
你可以获取给定时间的分钟,并按此值进行排序。

const getMinutes = s => s.split(':').reduce((h, m) => h * 60 + m);

var array = [{ time: "13:20", key2: "", key3: "" }, { time: "13:40", key2: "", key3: "" }, { time: "04:20", key2: "", key3: "" }];

array.sort((a, b) => getMinutes(a.time) - getMinutes(b.time));

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }


1
您可以在自定义回调函数中解析和排序每个项的time字段,如下所示:Array#sort()

const input = [ { time : "13:20" , key2: "", key3: ""},{ time : "13:40" , key2: "", key3: ""},{ time : "04:20" , key2: "", key3: ""}];


const output = input.sort((a, b) => {
  
  const [aHours, aMinutes] = a.time.split(':');
  const [bHours, bMinutes] = b.time.split(':');
  
  if(aHours < bHours) {
    return -1;
  }
  else if(aHours > bHours) {
    return 1;
  }
  else {
    
    if(aMinutes < bMinutes) {
      return -1;
    }
    else if(aMinutes > bMinutes) {
      return 1;
    }
  }
  
  return 0; 
});

console.log(output);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接