back to Overview

.filter()

Creates a new Minified list by taking an existing list and omitting certain elements from it.
Available in all modules.

Syntax Variants

list.filter(filterFunc)
list.filter(filterFunc, ctx)
list.filter(value)
_.filter(list, filterFunc)
_.filter(list, filterFunc, ctx)
_.filter(list, value)

Parameters

list
a list to filter. A list to use as input. Can be an array, a Minified list or any other array-like structure with length property.
filterFunc
The filter callback function(item, index) that decides which elements to include:
item
The current list element.
index
The second the zero-based index of the current element.
this
The given context if not null. Otherwise the list.
(callback return value)
true to include the item in the new list, false to omit it.
ctx (optional)
a context to pass to the callback as 'this'. Only supported in UTIL module.
value
a value to remove from the list. It will be determined which elements to remove using ==. Must not be a function. Requires Util module.
(return value)
the new, filtered list

Description

Creates a new Minified list by taking an existing list and omitting certain elements from it. You can either specify a callback function to approve those items that will be in the new list (all modules), or you can pass a value to remove from the new list (Util module only).

If the callback function returns true, the item is shallow-copied in the new list, otherwise it will be removed. For values, a simple equality operation (==) will be used.

Example

Removing all instances of the number 10 from a list:

var list = _([4, 10, 22, 7, 2, 19, 10]).filter(10);

Example

Removing all numbers over 10 from a list:

var list = _([4, 22, 7, 2, 19]).filter(function(item, index) {
    return item <= 10;
});

Example

The previous example with a native array is input. Note that the result is always a Minified list:

var list = _.filter([4, 22, 7, 2, 19], function(item, index) {
    return item <= 10;
});

Example

Creates a list of all unchecked checkboxes on a web page:

var list = $('input').filter(function(item, index) {
    return item.getAttribute('type') == 'checkbox' && item.checked;
});

See also..

  • only() offers selector-based filtering.

Comments

comments powered by Disqus

back to Overview

Functions