Friday, November 17, 2023

ColdFusion: Comparing a selected list vs an existing list and determining which needs to be inserted and deleted.

I've seen implementations in code, where in a database update all the records are deleted and new ones are inserted.   Here's a simple method in ColdFusion using underlying Java array methods for determining from a given selection list and current list, which items need to be deleted and inserted. 
<cfscript>
selectedList = "1,2,6"; 
currentList  ="1,2,3,4,5";
selectedArray = ListToArray(selectedList);
currentArray = ListToArray(currentList);
deleteArray = currentArray.clone();
deleteArray.RemoveAll(selectedArray);
insertArray = selectedArray.clone();
insertArray.RemoveAll(currentArray);
WriteOutput("selected");
WriteDump(selectedArray);
WriteOutput("Current");
WRiteDump(currentArray);
WRiteOutput("Deleted");
WriteDump(deleteArray.ToList());
WriteOutPut("Inserted");
WriteDump(insertArray.ToList());
</cfscript>