主题
filter
js
_.filter(collection, [predicate=_.identity])
迭代 collection
的元素,返回 predicate
返回真值的所有元素的数组。使用三个参数调用谓词:(value, index|key, collection)。
¥Iterates over elements of collection
, returning an array of all elements predicate
returns truthy for. The predicate is invoked with three arguments: (value, index|key, collection).
注意:与 _.remove
不同,此方法返回一个新数组。
¥Note: Unlike _.remove
, this method returns a new array.
新增于
¥Since
0.1.0
参数
¥Arguments
collection
(数组|对象):要迭代的集合。¥
collection
(Array|Object): The collection to iterate over.[predicate=_.identity]
(函数):每次迭代调用的函数。¥
[predicate=_.identity]
(Function): The function invoked per iteration.
返回
¥Returns
(数组):返回新的过滤数组。
¥(Array): Returns the new filtered array.
示例
¥Example
js
var users = [
{ 'user': 'barney', 'age': 36, 'active': true },
{ 'user': 'fred', 'age': 40, 'active': false }
];
_.filter(users, function(o) { return !o.active; });
// => objects for ['fred']
// The `_.matches` iteratee shorthand.
_.filter(users, { 'age': 36, 'active': true });
// => objects for ['barney']
// The `_.matchesProperty` iteratee shorthand.
_.filter(users, ['active', false]);
// => objects for ['fred']
// The `_.property` iteratee shorthand.
_.filter(users, 'active');
// => objects for ['barney']
// Combining several predicates using `_.overEvery` or `_.overSome`.
_.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]]));
// => objects for ['fred', 'barney']