forked from lodash/lodash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathremove.js
48 lines (45 loc) · 1.22 KB
/
remove.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
40
41
42
43
44
45
46
47
48
import basePullAt from './.internal/basePullAt.js'
/**
* Removes all elements from `array` that `predicate` returns truthy for
* and returns an array of the removed elements. The predicate is invoked
* with three arguments: (value, index, array).
*
* **Note:** Unlike `filter`, this method mutates `array`. Use `pull`
* to pull elements from an array by value.
*
* @since 2.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new array of removed elements.
* @see pull, pullAll, pullAllBy, pullAllWith, pullAt, reject, filter
* @example
*
* const array = [1, 2, 3, 4]
* const evens = remove(array, n => n % 2 == 0)
*
* console.log(array)
* // => [1, 3]
*
* console.log(evens)
* // => [2, 4]
*/
function remove(array, predicate) {
const result = []
if (!(array != null && array.length)) {
return result
}
let index = -1
const indexes = []
const { length } = array
while (++index < length) {
const value = array[index]
if (predicate(value, index, array)) {
result.push(value)
indexes.push(index)
}
}
basePullAt(array, indexes)
return result
}
export default remove