Skip to content

Instantly share code, notes, and snippets.

@shekhardtu
Last active September 4, 2019 18:30
Show Gist options
  • Save shekhardtu/f782ecc4c33898579652919cd50b28d1 to your computer and use it in GitHub Desktop.
Save shekhardtu/f782ecc4c33898579652919cd50b28d1 to your computer and use it in GitHub Desktop.
polyfill of filter in javascript
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