Vahe
Vahe

Reputation: 1841

JavaScript filter - What to return from jQuery filter callback method?

What do I need to return from my jQuery filter callback method in order to properly define the function, regardless if the result of the filter applied to my variable is not used after invocation of the filter method?

var results = [];
var filterResult = 0;

$(elem).each(function(){
    results.push($(this).val().trim().toLowerCase())
});
var string = event.target.value.trim().toLowerCase();

results.filter(function (r) {
   if(r == string)
       filterResult = filterResult + 1;
   return r;   //<-- what needs to be returned for this callback to be properly defined
});

Upvotes: 0

Views: 554

Answers (1)

rossipedia
rossipedia

Reputation: 59407

Array.prototype.filter creates a new Array by applying a function to each element of an existing array, and only including that element if the function returns true.

The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

For example:

var arr = [-3,-2,-1,0,1,2,3];
var positive = arr.filter(function (num) {
    return num > 0;
});
// num now contains: [1,2,3]

From your code snippet, that doesn't really seem like what you're trying to do. Rather it seems like you're trying to derive a single value from the elements of an array. In that case, what you want is Array.prototype.reduce:

var count = results.reduce(function (total, currentItem) {
    if (currentItem == string) {
        return total + 1;
    } else {
        return total;
    }
}, 0);

The second argument there (0) is the starting value of total.

Upvotes: 1

Related Questions