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;

Simple, yet useful tip. Happy Coding!


Leave a Comment

Your email address will not be published. Required fields are marked *