Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d800a3b

Browse files
Problme 7 solved
1 parent 45b31fd commit d800a3b

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/*
2+
3+
4+
5+
Given an integer array arr and a filtering function fn, return a filtered array filteredArr.
6+
7+
The fn function takes one or two arguments:
8+
9+
arr[i] - number from the arr
10+
i - index of arr[i]
11+
filteredArr should only contain the elements from the arr for which the expression fn(arr[i], i) evaluates to a truthy value. A truthy value is a value where Boolean(value) returns true.
12+
13+
Please solve it without the built-in Array.filter method.
14+
15+
16+
17+
Example 1:
18+
19+
Input: arr = [0,10,20,30], fn = function greaterThan10(n) { return n > 10; }
20+
Output: [20,30]
21+
Explanation:
22+
const newArray = filter(arr, fn); // [20, 30]
23+
The function filters out values that are not greater than 10
24+
Example 2:
25+
26+
Input: arr = [1,2,3], fn = function firstIndex(n, i) { return i === 0; }
27+
Output: [1]
28+
Explanation:
29+
fn can also accept the index of each element
30+
In this case, the function removes elements not at index 0
31+
Example 3:
32+
33+
Input: arr = [-2,-1,0,1,2], fn = function plusOne(n) { return n + 1 }
34+
Output: [-2,0,1,2]
35+
Explanation:
36+
Falsey values such as 0 should be filtered out
37+
38+
39+
Constraints:
40+
41+
0 <= arr.length <= 1000
42+
-109 <= arr[i] <= 109
43+
44+
45+
46+
47+
48+
*/
49+
50+
51+
52+
type Fn<T> = (ele: T, idx?: number, arr?:T[]) => boolean
53+
54+
function filter<T>(arr: T[], fn: Fn<T>) :T[] {
55+
const finalArr: T[] = [];
56+
57+
for(let i = 0; i < arr.length; i++) {
58+
const item = fn(arr[i], i);
59+
if (item) {
60+
finalArr.push(arr[i]);
61+
}
62+
}
63+
64+
return finalArr;
65+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /