AngularJS Custom filter to remove values


Example

A typical use case for a filter is to remove values from an array. In this example we pass in an array and remove any nulls found in it, returning the array.

function removeNulls() {
    return function(list) {
        for (var i = list.length - 1; i >= 0; i--) {
            if (typeof list[i] === 'undefined' ||
                    list[i] === null) {
                list.splice(i, 1);
            }
        }
        return list;
    };
}

That would be used in the HTML like

{{listOfItems | removeNulls}}

or in a controller like

listOfItems = removeNullsFilter(listOfItems);