簡體   English   中英

JavaScript - 從消息數組中獲取天數,不包括沒有消息的天數

[英]JavaScript - Get days from array of messages excluding days with no messages

我正在開發一個聊天應用程序,我有一組消息,每個消息都有一個時間戳屬性。 我需要在數組中獲取至少發送 1 條消息的所有日子,例如在 WhatsApp 中。 這個想法是在不同日期的消息之間顯示一個分隔符,分隔符就在指定日期的第一條消息之前。

例如,如果消息數組是

[
 {
  message: "Hey",
  timestamp: (1st January 2020)
 },
 {
  message: "Hi",
  timestamp: (1st January 2020)
 },
 {
  message: "Hello",
  timestamp: (3rd January 2020)
 },
]

那么預期的輸出將是

[(1st January 2020), (3rd January 2020)]

甚至更好

[
 {
  type: "Seperator",
  day: (1st January 2020)
 },
 {
  message: "Hey",
  timestamp: (1st January 2020)
 },
 {
  message: "Hi",
  timestamp: (1st January 2020)
 },
 {
  type: "Seperator",
  day: (3rd January 2020)
 },
 {
  message: "Hello",
  timestamp: (3rd January 2020)
 }
]

您需要做的就是檢查是否訪問了當前時間。 如果沒有,請添加分隔符。

let timestamps = [
 {
  message: "Hey",
  timestamp: '1st January 2020'
 },
 {
  message: "Hi",
  timestamp: '1st January 2020'
 },
 {
  message: "Hello",
  timestamp: '3rd January 2020'
 },
];

const separateTimestamps = ary => {
  let splitTimes = new Array();
  let timestamp;
  for (let i=0; i<ary.length; i++) {
    if (timestamp != ary[i].timestamp) {
      timestamp = ary[i].timestamp;
      splitTimes.push({
        type: 'Seperator',
        timestamp: timestamp
      });
    }

    splitTimes.push(ary[i]);
  }

  return splitTimes;
}


console.log(separateTimestamps(timestamps));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM