UNPKG

1.5 kBJavaScriptView Raw
1import arrayFilter from './_arrayFilter.js';
2import baseFilter from './_baseFilter.js';
3import baseIteratee from './_baseIteratee.js';
4import isArray from './isArray.js';
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 * **Note:** Unlike `_.remove`, this method returns a new array.
12 *
13 * @static
14 * @memberOf _
15 * @since 0.1.0
16 * @category Collection
17 * @param {Array|Object} collection The collection to iterate over.
18 * @param {Function} [predicate=_.identity] The function invoked per iteration.
19 * @returns {Array} Returns the new filtered array.
20 * @see _.reject
21 * @example
22 *
23 * var users = [
24 * { 'user': 'barney', 'age': 36, 'active': true },
25 * { 'user': 'fred', 'age': 40, 'active': false }
26 * ];
27 *
28 * _.filter(users, function(o) { return !o.active; });
29 * // => objects for ['fred']
30 *
31 * // The `_.matches` iteratee shorthand.
32 * _.filter(users, { 'age': 36, 'active': true });
33 * // => objects for ['barney']
34 *
35 * // The `_.matchesProperty` iteratee shorthand.
36 * _.filter(users, ['active', false]);
37 * // => objects for ['fred']
38 *
39 * // The `_.property` iteratee shorthand.
40 * _.filter(users, 'active');
41 * // => objects for ['barney']
42 */
43function filter(collection, predicate) {
44 var func = isArray(collection) ? arrayFilter : baseFilter;
45 return func(collection, baseIteratee(predicate, 3));
46}
47
48export default filter;