I think this entire added block can be replaced by something a bit more straightforward:

```
                // Filter out items that are already in the list. When appending results, we
                // skip the new results that already have an element with the same data-id attribute
                // in the list. When prepending results, we always add the new ones and remove the existing
                // elements with the same data-id attribute
                var $tmp = $('<div>').html(templateOutput);
                $tmp.children().each(function(index, newListItem) {
                    var id = $(newListItem).attr('data-id');
                    var $existing = $('li[data-id="' + id + '"]', $container);
                    if (id) {
                        if (prepend) {
                            $existing.remove();
                        } else if ($existing.length > 0) {
                            $(newListItem).remove();
                        }
                    }
                });
```