Last active
September 4, 2019 18:30
-
-
Save shekhardtu/f782ecc4c33898579652919cd50b28d1 to your computer and use it in GitHub Desktop.
polyfill of filter in javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Array.prototype.myFilter = function() { | |
var arr = this; | |
var len = arr.length; | |
var fn = arguments[0]; | |
var newArr = []; | |
for (var i=0; i<len; i++) { | |
if (fn(arr[i], i, arr)) { | |
newArr.push(arr[i]); | |
} | |
} | |
return newArr; | |
} | |
var arr = [1, 2, 3, 4, 5, 6, 7, 8]; | |
var filter = arr.filter((item)=>item % 2); | |
var myFilter = arr.myFilter((item)=>item % 2); | |
console.log(filter); | |
// [2,4,6,8] | |
console.log(myFilter); | |
// [2,4,6,8] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment