Functional Programming - Implement the filter Method on a Prototype

Array.prototype.myFilter = function(callback) {
  const newArray = [];
  // Only change code below this line
  for (let i = 0; i < this.length; i++) {
    if (Boolean(callback(this[i], i, this)) === true) {
  // Only change code above this line
  return newArray;

Please I don’t understand the ‘if’ line of code. Thanks

Can you be a little more specific about what you don’t understand?

Also, you need to use the triple back tick method to post your code in here. To display your code in here you need to wrap it in triple back ticks. On a line by itself type three back ticks. Then on the first line below the three back ticks paste in your code. Then below your code on a new line type three more back ticks. The back tick on my keyboard is in the upper left just above the Tab key and below the Esc key. You may also be able to use Ctrl+e to automatically give you the triple back ticks while you are typing in the this editor and the cursor is on a line by itself. Alternatively, with the cursor on a line by itself, you can use the </> button above the editor to add the triple back ticks.

Thank you for your response. I’d take note of the ticks in subsequent posts.

For the question. I don’t understand why Boolean should be added to the “if” condition since “if” already by default executes a block of code when the condition is true.

Also ‘this’ in that line of code represents what?

Basically i need help in reading the “if” line of code. That would really help. Thanks

if (Boolean(callback(this[i], i, this)) === true) {

This is an example of slightly overly verbose code. You could just use this instead:

if (callback(this[i], i, this)) {

Because the if statement looks to see if the return value of the callback is “truthy”, which is the same thing as passing it through the Boolean constructor. But in the original example, you must use the Boolean constructor because the comparison is being done with strict equality.

It represents the array that myFilter is being called on. If the array is defined as:

var arr = [23, 65, 98, 5];

And you use myFilter as:

const filteredArr = arr.myFilter(i => i > 50);

Then inside the myFilter method, this would be the array arr.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.