![](/img/trans.png)
[英]results “join” the array does not match the date in javascript from php
[英]javascript - join 2 array of date
我在Javascript中遇到DateTime
問題。 我的問題是我有2個DateTime
范圍數組。 例如:
var list1 = [
{start: 2018-08-28 00:00:00, end: 2018-08-28 04:00:00},
{start: 2018-08-28 04:00:00, end: 2018-08-28 10:00:00},
{start: 2018-08-28 12:00:00, end: 2018-08-28 14:00:00},
{start: 2018-08-28 20:00:00, end: 2018-08-28 22:00:00},
];
var list2 = [
{start: 2018-08-28 03:00:00, end: 2018-08-28 06:00:00},
{start: 2018-08-28 11:00:00, end: 2018-08-28 11:30:00},
{start: 2018-08-28 13:00:00, end: 2018-08-28 17:00:00},
];
合並兩個列表后,結果將是:
result = [
{start: 2018-08-28 00:00:00, end: 2018-08-28 03:00:00},
{start: 2018-08-28 03:00:00, end: 2018-08-28 04:00:00},
{start: 2018-08-28 04:00:00, end: 2018-08-28 06:00:00},
{start: 2018-08-28 06:00:00, end: 2018-08-28 10:00:00},
{start: 2018-08-28 11:00:00, end: 2018-08-28 11:30:00},
{start: 2018-08-28 12:00:00, end: 2018-08-28 13:00:00},
{start: 2018-08-28 13:00:00, end: 2018-08-28 14:00:00},
{start: 2018-08-28 14:00:00, end: 2018-08-28 17:00:00},
{start: 2018-08-28 20:00:00, end: 2018-08-28 22:00:00},
];
這是一個組合問題,而不是排序問題。 例如:從1:00-3:00與2:00-5:00相結合,結果將是:[1:00-2:00、2:00-3:00、3:00-5:00] 。
如果您有任何想法,請告訴我。
先感謝您!
您可以使用Array.concat組合兩個數組,然后使用自定義比較器對它們進行適當排序。
const output = list1.concat(list2).sort((a, b) => a.start - b.start);
現在建議使用ES6語法來連接2個數組:下面的示例
result = [...list1, ...list2];
result.sort(function(a,b){
// Turn your strings into dates and then subtract them
// to get a value that is either negative, positive, or zero.
return new Date(b.start) - new Date(a.start);
});
這里的問題是您有日期 ,而不是數字或字符串 ,這就是為什么排序不起作用的原因。 您可以將字符串設置為日期:
var list1 = [ {start: "2018-08-28 00:00:00", end: "2018-08-28 04:00:00"}, {start: "2018-08-28 04:00:00", end: "2018-08-28 10:00:00"}, {start: "2018-08-28 12:00:00", end: "2018-08-28 14:00:00"}, {start: "2018-08-28 20:00:00", end: "2018-08-28 22:00:00"}, ]; var list2 = [ {start: "2018-08-28 03:00:00", end: "2018-08-28 06:00:00"}, {start: "2018-08-28 11:00:00", end: "2018-08-28 11:30:00"}, {start: "2018-08-28 13:00:00", end: "2018-08-28 17:00:00"}, ]; var result = list1.concat(list2).sort((a, b) => new Date(a.start) - new Date(b.start)); console.log(result)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.