I have a webpage with two lists. A source list (represented by availableThings) populated by a search, and items that the user has selected (selectedThings). I want to maintain a unique list of selectedThings, so I want to remove already selected things from the list of available things. In my code snippet below, data.AvailableThings is populated from the server and has no knowledge of user-selected things. The user can select up to 3 items, ergo selectedThings.items will contain no more than 3 items. availableThings.items can potentially be a few thousand.
After availableThings.items gets populated, I feed it into ICanHaz for the HTML generation. FWIW, I’m using jQuery for drag behavior between the lists, but the question is jQuery-agnostic.
[... jQuery AJAX call snipped ...]
success: function (data) {
availableThings.items = [];
for (var thing in data.AvailableThings) {
var addToList = true;
for (var existing in selectedThings.items) {
if (existing.Id === thing.Id) {
addToList = false;
break;
}
}
if (addToList) {
availableThings.items.push(thing);
}
}
}
If n is the count of available things and m is the count of selected things, then this is O(n * m) whereas if you hashed by ID, you could turn this into O(n + m).