想要从打字稿中的json数组中删除重复的值

时间:2018-07-09 06:11:51

标签: arrays json typescript

要从阵列中删除重复项
 我要删除其中之一。同样,当有多个重复项时,我只想保留第一个对象,因为我将数组按时间降序排列。

这是我的代码:

 chatlist   : [
      {
        "receiver": "Remya",
        "message": "hiiiii",
        "created": "2018-07-09T05:22:28.143Z"
      },
      {
        "sender": "Remya",
        "message": "hi",
        "created": "2018-07-07T10:35:08.919Z"
      },
      {
        "sender": "Mini",
        "message": "hi",
        "created": "2018-07-05T08:42:50.189Z"
      },
      {
        "sender": "Mini",
        "message": "hlo",
        "created": "2018-07-05T05:11:40.331Z"
      },
      {
        "receiver": "Mini",
        "message": "hi",
        "created": "2018-07-05T05:11:34.489Z"
      },
      {
        "receiver": "Maya",
        "message": "hlo",
        "created": "2018-07-04T05:23:35.650Z"
      },
      {
        "sender": "Maya",
        "message": "hi",
        "created": "2018-07-04T05:22:21.723Z"
      },
      {
        "sender": "Mini",
        "message": "hello",
        "created": "2018-07-04T05:20:06.341Z"
      },
      {
        "receiver": "Mini",
        "message": "hi",
        "created": "2018-07-04T05:19:32.964Z"
      }
    ]

我想要类似的输出

    chatlist   : [
  {
    "receiver": "Remya",
    "message": "hiiiii",
    "created": "2018-07-09T05:22:28.143Z"
  },
{
    "sender": "Mini",
    "message": "hi",
    "created": "2018-07-05T08:42:50.189Z"
  },
{
    "receiver": "Maya",
    "message": "hlo",
    "created": "2018-07-04T05:23:35.650Z"
  }
]

我正在尝试执行我的聊天列表页面。所以我需要将最近的聊天记录加载为列表。

预先感谢

1 个答案:

答案 0 :(得分:0)

这是我的建议。

您遍历chatList(data)。如果找到新的发送者或接收者,请将其存储在两个列表之一(knownSendersknownReceivers)中,然后将聊天项放入finalChatList中。如果发件人或收件人重复,则聊天项将被忽略,因为filter方法返回的列表长度大于0。

let knownSenders = [];
let knownReceivers = [];
let finalChatList = [];
const data = JSON.parse(chatList);

data.forEach( element => {
    const sender = element.sender ? element.sender : null;
    const receiver = element.receiver ? element.receiver : null;

    if (sender) {
        if (knownSenders.filter( el => el.sender === sender).length <= 0) {
            // sender yet unknown
            knownSenders.push(sender);
            finalChatList.push(element);
        }
    } else if  (receiver) {
        if (knownReceivers.filter( el => el.receiver === receiver).length <= 0) {
            // receiver yet unknown
            knownReceivers.push(receiver);
            finalChatList.push(element);
        }
    }
});