_.remove(array, [predicate=_.identity])
33
_.remove(array, [predicate=_.identity])
_.remove删除所有predicate处理后返回true的数组元素,返回值是被删除元素组成的数组,predicate函数接受三个参数,当前元素值,元素索引,数组本身
参数
array (Array): 需要修改的数组
[predicate=_.identity] (Function): 判断每个元素的遍历器
返回值
(Array):返回删除元素后的原数组
例子
var array = [1, 2, 3, 4]; var evens = _.remove(array, function(n) { return n % 2 == 0; }); console.log(array); // => [1, 3] console.log(evens); // => [2, 4]
源代码:
basePullAt之前看过了,这里省略
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] */ //删除所有predicate处理后返回true的数组元素,返回值是被删除元素组成的数组 //predicate函数接受三个参数,当前元素值,元素索引,数组本身 function remove(array, predicate) { const result = []//被删除的元素存放的数组,最后会被返回 if (!(array != null && array.length)) {//如果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)) {//如果根据当前值调用predicate后返回true,result数组里push进值,indexed数组里push进索引 result.push(value) indexes.push(index) } } basePullAt(array, indexes)//调用basePullAt删除所有索引对应的值 return result//返回被删除的元素组成的数组 } export default remove