UNPKG

1.43 kBJavaScriptView Raw
1import arrayFilter from './_arrayFilter';
2import baseFilter from './_baseFilter';
3import baseIteratee from './_baseIteratee';
4import isArray from './isArray';
5
6/**
7 * Iterates over elements of `collection`, returning an array of all elements
8 * `predicate` returns truthy for. The predicate is invoked with three
9 * arguments: (value, index|key, collection).
10 *
11 * @static
12 * @memberOf _
13 * @since 0.1.0
14 * @category Collection
15 * @param {Array|Object} collection The collection to iterate over.
16 * @param {Array|Function|Object|string} [predicate=_.identity]
17 * The function invoked per iteration.
18 * @returns {Array} Returns the new filtered array.
19 * @example
20 *
21 * var users = [
22 * { 'user': 'barney', 'age': 36, 'active': true },
23 * { 'user': 'fred', 'age': 40, 'active': false }
24 * ];
25 *
26 * _.filter(users, function(o) { return !o.active; });
27 * // => objects for ['fred']
28 *
29 * // The `_.matches` iteratee shorthand.
30 * _.filter(users, { 'age': 36, 'active': true });
31 * // => objects for ['barney']
32 *
33 * // The `_.matchesProperty` iteratee shorthand.
34 * _.filter(users, ['active', false]);
35 * // => objects for ['fred']
36 *
37 * // The `_.property` iteratee shorthand.
38 * _.filter(users, 'active');
39 * // => objects for ['barney']
40 */
41function filter(collection, predicate) {
42 var func = isArray(collection) ? arrayFilter : baseFilter;
43 return func(collection, baseIteratee(predicate, 3));
44}
45
46export default filter;