- Published on
Polyfill for filter function in JavaScript
- Authors
- Name
- Mrinmay Mukherjee
- @devmrin
Naive Implementation
myFilter.js
Array.prototype.myFilter = function (callbackFn, thisArg) {
let array = this;
let returnedArray = [];
for (let i = 0; i < array.length; i++) {
let callbackArguments = [array[i], i, array];
if (thisArg) {
if(callbackFn.call(thisArg, ...callbackArguments)){
returnedArray.push(array[i]);
};
} else {
if(callbackFn(...callbackArguments)){
returnedArray.push(array[i]);
};
}
}
return returnedArray;
};
Syntax to fulfill
// Arrow function
filter((element) => {
/* ... */
})
filter((element, index) => {
/* ... */
})
filter((element, index, array) => {
/* ... */
})
// Callback function
filter(callbackFn)
filter(callbackFn, thisArg)
// Inline callback function
filter(function (element) {
/* ... */
})
filter(function (element, index) {
/* ... */
})
filter(function (element, index, array) {
/* ... */
})
filter(function (element, index, array) {
/* ... */
}, thisArg)