Skip to content

Commit db155f8

Browse files
authored
Merge pull request #17 from praffn/array-filter
Add Array.prototype.filter implementation
2 parents 48a92a7 + 36976bc commit db155f8

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

implementations/filter.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
*
3+
filter() creates a new array with each element in the original
4+
array if and only if the element pass the supplied predicate callback.
5+
6+
The predicate callback is invoked with three arguments:
7+
8+
- the value of the element
9+
- the index of the element
10+
- the Array object being traversed
11+
12+
The predicate callback is expected to return true if the element should
13+
appear in the new array, otherwise false.
14+
15+
You can optionally specify a value to use as `this` in the callback
16+
as the second argument to filter().
17+
18+
If no elements pass the predicate callback, an empty array will be returned
19+
*/
20+
21+
Array.prototype.myFilter = function myFilter(callback, thisArg) {
22+
const newArray = [];
23+
for (let i = 0; i < this.length; i += 1) {
24+
if (callback.call(thisArg, this[i], i, this)) {
25+
newArray.push(this[i]);
26+
}
27+
}
28+
return newArray;
29+
};

0 commit comments

Comments
 (0)