Using Array.prototype.filter() with arguments

In JavaScript, the filter() method is used to search for array items which satisfy the condition that is passed to it. Technically this method creates a new array with all elements that pass the test implemented by the provided function. But there is a confusion around how to use it with arguments. For example, we want to search for an employee with id = 101 in an array of employee objects.
Let us see the typical use of Array.prototype.filter().
function isBigEnough(element) {
return element >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]

Now, we shall see how to implement it with arguments.

function GetEmployee(EmpId) {
    return function(element) {
        if(element.ID === EmpId)
        {
             return element;
        }
    }
}
employeeArray.filter(GetEmployee(101));

Simple, yet useful tip. Happy Coding!

Resources: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s