0

I have two arrays that contain a list of "message" objects. Each message object has a property 'receivedTime'.

I can sort the two arrays by 'receivedTime' so that newest messages are first.

Now, using underscorejs (if applicable)...is there a way I can pop off the difference in the two arrays? The newer array will have newer messages than the original list.

I only want new messages that are not in the original array.

For some context, I can only get all messages from the API. so I need to keep doing that in a timer, and add any new messages to the table on the page (this part I can do, I just need the difference in the list from one call to the next).

4

4 回答 4

2

recievedTime 的格式是什么?如果是时间戳,那么如何保存最后一个接收时间并查询列表以仅过滤新的。

您可以使用纯 javascript

var newones = items.filter( function(item){return (item.recievedTime>lastRecievedTime);} );
于 2013-09-05T06:04:36.380 回答
0

对两个数组进行排序后,将它们传递给 for 循环并检查值是否在第二个数组中。

for(var i = 0; i < newMessages.length; i++) {
    if(Messages[i] == newMessages[i]) {
         newMessages.splice(i, 1);
    }
}

否则查找消息的长度并删除 newMessages 数组中存在的元素数量。

于 2013-09-05T06:01:09.663 回答
0

尝试使用filter然后指定一个函数,该函数只返回那些不在原始数组中的函数,类似于以下内容:

_.filter(newer_array, function(message) {
    return _.contains(older_array,message); 
});
于 2013-09-05T06:01:52.367 回答
0

或者,另一种选择是......在对两个数组进行排序后,在“旧”数组中找到最新消息的接收时间,然后遍历“新”数组,直到你到达之前找到的接收时间。沿着这些路线的东西......

var split = older[0].receivedTime
var difference = []

var i = 0
while(newer[i].receivedTime !== split) {
    difference.push(newer[i]);
}
于 2013-09-05T06:08:56.093 回答