Filter's Callback Parameters
What you'll learn: You'll discover the three parameters that filter automatically passes to your callback function.
The Three Parameters Filter Provides
Just like map, the filter method passes three pieces of information to your callback function on every iteration:
- element (or currentValue) – The current item being tested
- index – The position of that element in the array
- array – The entire original array being filtered
Most of the time, you'll only need the first parameter (the element itself), but the other two are available whenever you need them.
The Syntax
array.filter(function(element, index, array) {
// Return true to keep element, false to exclude it
});
Practical Example
const scores = [85, 92, 78, 95, 88];
// Using only the element
const passing = scores.filter(function(score) {
return score >= 80;
});
// [85, 92, 95, 88]
// Using element and index
const topHalf = scores.filter(function(score, index) {
return index < scores.length / 2;
});
// [85, 92] - first half of array
// Using all three parameters
const highWithContext = scores.filter(function(score, index, allScores) {
const average = allScores.reduce((sum, s) => sum + s, 0) / allScores.length;
return score > average;
});
// [92, 95, 88] - above the average of 87.6
Think of it like a security checkpoint: each person (element) gets checked at a specific position (index), and the guard has access to the complete guest list (array) if needed for context.
Key Takeaway: Filter passes the same three parameters as map — element, index, and array — giving you flexibility to make filtering decisions based on value, position, or context.