Yes, you can certainly call any other functions inside a filter callback.
The only thing you're missing is that the callback needs to return a value. Your callback doesn't have a return statement. It calls the filterCreatures() function, but then it discards the value returned by that function and by default returns undefined.
Compare with the original version of your code:
creatures.filter(filterCreatures);
In this code, filter() calls the filterCreatures function directly and then uses its return value to decide whether to include the element. You don't see this explicitly in the code, but filter() is looking for that return value.
Here's an exercise to help clarify this. Take your broken code and move the inline filter callback out to a named function. We'll call it filterCreaturesWrapper. So instead of this:
filterCreatures = function(v) {
return v.species === 'Zombie';
}
zombieCreatures = creatures.filter(function(v) {
filterCreatures(v);
});
we have this:
filterCreatures = function(v) {
return v.species === 'Zombie';
}
filterCreaturesWrapper = function(v) {
filterCreatures(v);
}
zombieCreatures = creatures.filter(filterCreaturesWrapper);
If you study that, you'll see it's exactly the same code as before, we just moved it around a little. filterCreaturesWrapper is the same function that was inline inside the .filter() call. And now the problem should jump out at us: filterCreatures has a return statement and filterCreaturesWrapper doesn't.
Going back to the original broken code, it's as if we had written:
zombieCreatures = creatures.filter(function(v) {
filterCreatures(v);
return undefined; // .filter treats this as 'false'
});
So just add a return in your callback and it works:
'use strict';
var creatures = [], zombieCreatures = [];
var filterCreatures;
creatures = [
{species: 'Zombie', hitPoints: 90},
{species: 'Orc', hitPoints: 40},
{species: 'Skeleton', hitPoints: 15},
{species: 'Zombie', hitPoints: 85}
];
filterCreatures = function(v) {
return v.species === 'Zombie';
}
zombieCreatures = creatures.filter(function(v) {
return filterCreatures(v); // <-- added "return"
});
console.log(zombieCreatures);
Not every language works like this. Ruby, for example, returns the last expression in a method (function) whether you explicitly say return or not. So if you were writing Ruby code (assuming all the other bits were converted to Ruby too), your code would have worked!