Deselecting multi-select lookup via other multi-select lookup

Deselecting multi-select lookup via other multi-select lookup

Hi, I would like to use a multi-select lookup to populate another multi-select lookup: select a Unit, and automatically a Name is selected. I've created below on user input of field.

Problem: everything works as planned, both when I add or remove items from the Unit field the Name field gets populated (or removed). However, if I add items and subsequently remove them from the Unit field, once I get to removing the last remaining item in the Unit Field, the Name field does not get fully cleared. There is always still 1 name remaining even though the Unit field is empty.

input.Name.clear();
if(Unit != null)
{
for each  selectedunit in input.Unit
{
previousnames = input.Name;
contract = AddRentalContract[Unit = selectedunit].Main_tenant;
selectedname = AddTenant[ID = contract].ID;
previousnames.add(selectedname);
input.Name = previousnames;
}
}