Checking array for tags I call a service which returns an array of tags. The array may be empty, and if so, it just saves the tag. Otherwise, it checks if the tag is in the array. If so, then the tag is removed, otherwise it's saved.

Can this be optimized for efficiency?

function processTag(total, tag, associatedTicker) {
    var foundFlag = false;

    TagFactory.retrieveTickerTags('onlyTags').then(function(data) {
        console.log('onlyTags data',data);

        // Is there are selected Tags:
        if (data.length &gt; 0) {
            // Search for tag in tagFactory
            for (var i=0; i&lt;data.length; i++) {
                if (data[i].term_id === tag.term_id) {
                    foundFlag = true;
                    break;
                }
            }
            // If found, remove tag:
            if (foundFlag) {
                removeTag(tag, associatedTicker);
            }
            else {
                // Save the tag:
                if (total &lt; 3) {
                    saveTag(tag, associatedTicker);
                }
                // 3 are already selected, display alert:
                else {
                    displayAlert('failure', 'Only 3 tags can be monitored at a time.');
                }
            }
        }
        // Else if there are no selected tags:
        else {
            saveTag(tag, associatedTicker);
        }
    });
}
Here's a rewrite that clarifies and shortens the code.  A few of its advantages:


Removes nested if... else statements
Replaces vague variable name data with something more descriptive.
Names the concepts you are implicitly using in your code (eg, "checkedSave" means "check if it's valid to save the tag, then save it").  We also name the various conditions we are interested in: noSavedTags and tagAlreadyExists.
Avoid unnecessary indendation by not defining our callback saveOrRemoveTag inline.
Avoid verbose, unsightly for loop by using using map and indexOf to check if the tag already exists.
User ternary operator instead of if... else to express simple conditional expressions.


The new code:

function processTag(total, tag, associatedTicker) {

    TagFactory.retrieveTickerTags('onlyTags').then(saveOrRemoveTag);

    function saveOrRemoveTag(savedTags) {

        var noSavedTags = savedTags.length == 0;
        if (noSavedTags) { checkedSave(); return; }

        tagAlreadyExists() ? removeTag(tag, associatedTicker) : checkedSave();

        // the 3 lines above are really the entire function
        // everything below is just helper functions

        function checkedSave() {
            total &lt; 3 ? saveTag(tag, associatedTicker)
                      : displayAlert('failure', 'Only 3 tags can be monitored at a time.');
        }

        function tagAlreadyExists() {
            var existingTermIds = savedTags.map(function(t) { return t.term_id });
            return existingTermIds.indexOf(tag.term_id) &gt; -1;
        }
    }
}