Skip to content

Commit e65af79

Browse files
author
munnasorder
committed
add find, filter, findIndex method
1 parent 952d271 commit e65af79

File tree

3 files changed

+73
-0
lines changed

3 files changed

+73
-0
lines changed

filter.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
const myArray = [1,2,3,4,5,6,7,8,9];
2+
3+
// example 1
4+
Array.prototype.myFind = function(cb) {
5+
let result = [];
6+
for (let i = 0, length = this.length; i < length; i++) {
7+
if (cb(this[i], i, this)) result.push(this[i]);
8+
};
9+
return result;
10+
}
11+
const result = myArray.filter((doc, i, arr) => doc > 3);
12+
console.log(result)
13+
// output [ 4, 5, 6, 7, 8, 9 ]
14+
15+
// example 2
16+
function myOwnFilter(arr, cb) {
17+
let result = [];
18+
for (let i = 0, length = arr.length; i < length; i++) {
19+
if (cb(arr[i], i, arr)) result.push(arr[i]);
20+
}
21+
return result;
22+
}
23+
const result2 = myOwnFilter(myArray, (doc, i, arr) => doc > 5);
24+
console.log(result2)
25+
// output [ 6, 7, 8, 9 ]

find.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
const myArray = [1,2,3,4,5,6,7,8,9];
2+
3+
// example 1
4+
Array.prototype.myFind = function(cb) {
5+
for (let i = 0, length = this.length; i < length; i++) {
6+
if (cb(this[i], i, this)) return this[i];
7+
};
8+
};
9+
10+
const result = myArray.myFind((doc, i, arr) => doc > 9);
11+
console.log(result);
12+
// output undefined
13+
14+
15+
// example 2
16+
function myOwnMap(arr, cb) {
17+
for (let i = 0, length = arr.length; i < length; i++) {
18+
if (cb(arr[i], i, arr)) return arr[i];
19+
}
20+
}
21+
22+
const result2 = myOwnMap(myArray, (doc, i, arr) => doc > 2);
23+
console.log(result2);
24+
// output 3

findIndex.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
const myArray = [1,2,3,4,5,6,7,8,9];
2+
3+
// example 1
4+
Array.prototype.myFindIndex = function(cb) {
5+
for (let i = 0, length = this.length; i < length; i++) {
6+
if (cb(this[i], i, this)) return i;
7+
}
8+
return -1;
9+
}
10+
const result = myArray.myFindIndex((doc, i, arr) => doc === 5);
11+
console.log(result)
12+
// output 4
13+
14+
// example 2
15+
function myOwnFindIndex(arr, cb) {
16+
for (let i = 0; i < arr.length; i++) {
17+
if (cb(arr[i], i, arr[i])) return i;
18+
}
19+
return -1;
20+
}
21+
22+
const result2 = myOwnFindIndex(myArray, (doc, i, arr) => doc === 8);
23+
console.log(result2);
24+
// output 7

0 commit comments

Comments
 (0)