_.filter(collection, [predicate=_.identity])
69
_.filter(collection, [predicate=_.identity])
_.filter和原生的filter方法类似,遍历数组,将predicate处理后结果为真值的元素组成一个新数组返回
参数
collection (Array|Object): 需要遍历的集合
[predicate=_.identity] (Function):每一次遍历调用的方法
返回值
(Array): 返回过滤后的新数组
例子
var users = [ { 'user': 'barney', 'age': 36, 'active': true }, { 'user': 'fred', 'age': 40, 'active': false } ]; _.filter(users, function(o) { return !o.active; }); // => objects for ['fred'] // The `_.matches` iteratee shorthand. _.filter(users, { 'age': 36, 'active': true }); // => objects for ['barney'] // The `_.matchesProperty` iteratee shorthand. _.filter(users, ['active', false]); // => objects for ['fred'] // The `_.property` iteratee shorthand. _.filter(users, 'active'); // => objects for ['barney']
源代码:
省略iteratee的处理,想看iteratee的处理看这里,https://www.cnblogs.com/hahazexia/p/9901435.html
/** * 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'] */ //和原生的filter方法类似,遍历数组,将predicate处理后结果为真值的元素组成一个新数组返回 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)) {//如果predicate返回true,就把当前元素加入结果数组 result[resIndex++] = value } } return result } export default filter

浙公网安备 33010602011771号