UNPKG

1.35 kBJavaScriptView Raw
1import baseIteratee from './_baseIteratee';
2import basePullAt from './_basePullAt';
3
4/**
5 * Removes all elements from `array` that `predicate` returns truthy for
6 * and returns an array of the removed elements. The predicate is invoked
7 * with three arguments: (value, index, array).
8 *
9 * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull`
10 * to pull elements from an array by value.
11 *
12 * @static
13 * @memberOf _
14 * @since 2.0.0
15 * @category Array
16 * @param {Array} array The array to modify.
17 * @param {Array|Function|Object|string} [predicate=_.identity]
18 * The function invoked per iteration.
19 * @returns {Array} Returns the new array of removed elements.
20 * @example
21 *
22 * var array = [1, 2, 3, 4];
23 * var evens = _.remove(array, function(n) {
24 * return n % 2 == 0;
25 * });
26 *
27 * console.log(array);
28 * // => [1, 3]
29 *
30 * console.log(evens);
31 * // => [2, 4]
32 */
33function remove(array, predicate) {
34 var result = [];
35 if (!(array && array.length)) {
36 return result;
37 }
38 var index = -1,
39 indexes = [],
40 length = array.length;
41
42 predicate = baseIteratee(predicate, 3);
43 while (++index < length) {
44 var value = array[index];
45 if (predicate(value, index, array)) {
46 result.push(value);
47 indexes.push(index);
48 }
49 }
50 basePullAt(array, indexes);
51 return result;
52}
53
54export default remove;