# \_.filter（过滤数组或者对象）

**语法：**

```javascript
_.filter(collection, [predicate=_.identity])
```

**源代码链接：**[source](https://github.com/lodash/lodash/blob/4.17.10/lodash.js#L9171)

**npm包链接：**[npm package](https://www.npmjs.com/package/lodash.filter)

**描述：**

遍历`collection`（集合）元素，返回`predicate`（断言函数）返回真值 的所有元素的数组。 predicate（断言函数）调用三个参数：*(value, index|key, collection)*。

**Note:**

与[`_.remove`](https://lodash.com/docs/4.17.10#remove)不同, 这个方法返回一个新数组.

**开始版本：**&#x30;.1.0

**参数：**

* `collection (Array|Object)`: 一个用来迭代的集合。
* `[predicate=_.identity] (Array|Function|Object|string)`: 每次迭代调用的函数。

**返回值：**

* `(Array)`: 返回一个新的过滤后的数组。

**例子：**

```javascript
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']
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://lodash.shujuwajue.com/collection/filter.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
