Reputation: 75686
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).
Upvotes: 0
Views: 153
Reputation: 433
Or, another option would be.. after sorting both arrays, find the receivedTime of the newest message in the "older" array, and then iterate through the "newer" array until you get to the receivedTime found earlier. Something along these lines...
var split = older[0].receivedTime
var difference = []
var i = 0
while(newer[i].receivedTime !== split) {
difference.push(newer[i]);
}
Upvotes: 0
Reputation: 1712
What is format of recievedTime ? if it's timestamp then , How about saving last recievedTime and querying list to filter only new ones.
You can use pure javascript
var newones = items.filter( function(item){return (item.recievedTime>lastRecievedTime);} );
Upvotes: 2
Reputation: 433
Try using filter
and then specifying a function that returns only those not in the original array, something along the lines of this:
_.filter(newer_array, function(message) {
return _.contains(older_array,message);
});
Upvotes: 0
Reputation: 10030
After sorting both arrays, pass them to for loop and check if value is in second array.
for(var i = 0; i < newMessages.length; i++) {
if(Messages[i] == newMessages[i]) {
newMessages.splice(i, 1);
}
}
Else find length of Messages and remove that number of elements present in newMessages array.
Upvotes: 0