Skip to main content

Array.filter

The Array.prototype.filter method creates a new array with all elements that pass the test implemented by the provided function.

Code

Array.prototype.myFilter = function (callbackFn) {
var arr = [];
for (var i = 0; i < this.length; i++) {
if (callbackFn.call(this, this[i], i, this)) {
arr.push(this[i]);
}
}
return arr;
};

Explanation:

  1. Initialization:
  • var arr = []; initializes a new empty array to store the elements that pass the test.
  1. Loop through the array:
  • for (var i = 0; i < this.length; i++) { ... } iterates over each element in the array.
  1. Callback Execution and Condition Check:
  • if (callbackFn.call(this, this[i], i, this)) { ... } calls the provided function callbackFn with three arguments:

    • this[i]: the current element.
    • i: the index of the current element.
    • this: the array being processed.
  • callbackFn.call(this, this[i], i, this) is wrapped in a call to ensure the this context is correctly set when the callback is executed.

  • The condition if (callbackFn.call(this, this[i], i, this)) checks if the current element passes the test defined in the callback function.

  1. Push Elements:
  • arr.push(this[i]); adds the current element to the new array if it passes the test (i.e., if the callback returns true).
  1. Return New Array:
  • return arr; returns the new array containing only the elements that passed the test.