I have two lists in javascript that are of same structure like below:
var required_documents = [{"id":1,"dt":1},{"id":2,"dt":2},{"id":3,"dt":3}];
var existing_documents = [{"id":1,"dt":1},{"id":2,"dt":2},{"id":3,"dt":4}];
I need to remove all records from database that are in existing documents list (i.e "dt") but NOT in required_documents list.
For the above scenario I should remove only {"id":3,"dt":4} and insert {"id":3,"dt":3}. I am not sure how I can compare on just one property. This is below that I found on SOF sometime ago but can’t find it again apologies for not referencing it.
required_documents.forEach((obj) => {
const elementInArr2 = existing_documents.find((o) => o.dt === obj.dt);
console.log('found elementinarr: ' + obj.dt);
});
This returns unique objects like dt:1,dt:2,dt:3 but I need dt:4 from the existing documents list as it is the one that is not in the required documents list and needs to be deleted. How can I get just the one that is not in the required documents list.
4
Answers
If you don’t care about time complexity, something this should work:
Edit Okay, I just reread your question and I’m a bit confused. Do you want the object
{id: 3, dt: 3}
inside the new array as well?You need to run it twice to confirm there is no elements left in existing. So create a function and use it.
Assuming both
id
anddt
properties are significant, I would first create a means of hashing an entry and then build a hashed set ofrequired_documents
.Then you can filter out anything from
existing_documents
that is in the set, leaving only the results you want.The hash creation can be anything that produces a comparable entity that can uniquely identify a record.
You can do like below