# 2634.Filter Elements from Array
###### tags:`Array` | `leetCode`
<font color="#01AE9A" background="E1F3F0">`easy`</font>
### 題目
Given an integer array arr and a filtering function fn, return a new array with a fewer or equal number of elements.
The returned array should only contain elements where fn(arr[i], i) evaluated to a truthy value.
Please solve it without the built-in Array.filter method.
`returnedArray[i] = fn(arr[i], i)`.
Please solve it without the built-in `Array.map` method.
### Example
```javascript=
Input: arr = [0,10,20,30], fn = function greaterThan10(n) { return n > 10; }
Output: [20,30]
Explanation:
const newArray = filter(arr, fn); // [20, 30]
The function filters out values that are not greater than 10
```
```javascript=
Input: arr = [1,2,3], fn = function firstIndex(n, i) { return i === 0; }
Output: [1]
Explanation:
fn can also accept the index of each element
In this case, the function removes elements not at index 0
```
```javascript=
Input: arr = [-2,-1,0,1,2], fn = function plusOne(n) { return n + 1 }
Output: [-2,0,1,2]
Explanation:
Falsey values such as 0 should be filtered out
```
### Constraints
- `0 <= arr.length <= 1000`
- `-109 <= arr[i] <= 109`
---
### 解題邏輯
這題函式接受一個數字 `arr`和一個 `callback function`當作參數
```javascript=
var filter = function(arr, fn) {
let newArray =[]
for(let i = 0;i <arr.length;i++){
if(fn(arr[i], i)){
newArray.push(arr[i])
}
}
return newArray
};
```

跟 [Day4](https://hackmd.io/Zb9OCwYdQgiv_JSRDxTH8w)類似,只不過這題是用 arr 裡面的數字去跑 fn ,true 才把數字 push 到 newArry 裏面
{"metaMigratedAt":"2023-06-18T03:48:39.456Z","metaMigratedFrom":"Content","title":"2634.Filter Elements from Array","breaks":true,"contributors":"[{\"id\":\"da4833e9-8c75-4c4a-9870-e972056b78eb\",\"add\":1578,\"del\":0}]"}