Javascript Array.filter

We will discuss Polyfill for Array.filter().

About

The Javascript filter takes a function as a parameter and returns a new array with items that satisfy the given function .i.e return true when the item is passed to a given function.

const arr = [0,2,3,4]

console.log(arr.filter( item => item%2))
console.log(arr)

In the above function only 3%2 returns 1 which JS takes as true and the rest of all returns 0 which is false so the output is [3]

Polyfill

  1. Return new array

  2. Check if the element is an array

  3. Return all the items satisfying the given function.

Array.prototype.customFilter = function(filterFn){
    let output = []
    if(!Array.isArray(this)){
        return Exception(`${this}.customFilter is not a function`)
    }
    this.forEach((item)=>{
        if(filterFn(item)){
            output.push(item)
        }
    })
    return output
}

Here we are looping the given array and checking if the item satisfies the given function. If yes then add it to the output array otherwise, ignore.

// Sample output
console.log(arr.customFilter( item => item%2))
// [ 3, 1.2, -1, 5 ]

Hit ❤️ to encourage me to add more Polyfills.