forked from lodash/lodash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
filter.js
39 lines (37 loc) · 1.04 KB
/
filter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* Iterates over elements of `array`, returning an array of all elements
* `predicate` returns truthy for. The predicate is invoked with three
* arguments: (value, index, array).
*
* **Note:** Unlike `remove`, this method returns a new array.
*
* @since 5.0.0
* @category Array
* @param {Array} array The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
* @see pull, pullAll, pullAllBy, pullAllWith, pullAt, remove, reject
* @example
*
* const users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false }
* ]
*
* filter(users, ({ active }) => active)
* // => objects for ['barney']
*/
function filter(array, predicate) {
let index = -1
let resIndex = 0
const length = array == null ? 0 : array.length
const result = []
while (++index < length) {
const value = array[index]
if (predicate(value, index, array)) {
result[resIndex++] = value
}
}
return result
}
export default filter