user2994560 user2994560 -4 years ago 321
Javascript Question

JavaScript remove object from array if value exists in other array

I am using Firebase, so if there is a more efficient way to structure this data in order to be able to query only the cards that have not already been viewed by the logged in user, I am open to going that route as well. Right now I am trying to do the filtering after the fact.

I have an array of all cards included in my application that looks like this:

enter image description here

I have a second array that holds information on all the cards the user has already seen. I want to be able to look through both arrays, and if the cid in Array two matches the $id in Array 1, then remove that object entirely from Array 1.

enter image description here

Answer Source

Loop through the arrays and use splice to remove the element

for(var i =0; i< array2.length; i++ ) {
   for(var j= 0; j< array1.length;j++) {
     if (array2[i].$id === array1[j].$id) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download