skip to Main Content
Array.prototype.myFilter = function (callback) {
    const newArray = [];
    // Only change code below this line
    for (let i = 0; i < this.length; i++) {
      if (callback(this[i], i, this) == true) {
        newArray.push(this[i]);
      }
    }
    //This function works like filter()
    return newArray;
  };

I need help to understand how callback function works, and how we can implement it?

The code that was given above is just an example, I just need help with this topic

Dont be haters, I need explanations, I am just an entry-level javascript programmer

Thanks

2

Answers


  1. Since you are a beginner I suppose you need explanation not the coding part. So here it is:

    Any function that is passed into the argument of some other function like suppose you have this type of function " FunctionA(functionB) is referred to as the call back function.

    These functions play a pivotal role in javascript since they allow dynamic programming to be implemented at best.

    In your case, you are using myFilter method that works similar to the filter method in javascript.
    You can filter the elements based on the specific condition that you provide to this filter method.

    I hope you will get a better understanding now. Thanks

    Login or Signup to reply.
  2. This can work, here in the test function we keep only the elements with a length greater than 4 letters so it will return :
    Array [ "bacon", "eggs bacon spam and sausage" ]

            Array.prototype.myFilter = function (callback) {
              const newArray = [];
    
              for (let i = 0; i < this.length; i++) {
                if (callback(this[i], i, this) == true) {
                  newArray.push(this[i]);
                }
              }
    
                return newArray;
            };
    
            function test(element, index, array) {
              return element.length > 4;
            }
    
            let foo = ["Shop", "eggs", "bacon", "spam", "eggs bacon spam and sausage"];
            let filteredArray = foo.myFilter(test);
    
            console.log(filteredArray);

    Have a nice day.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search