Javascript Filter function

Filter

On to the .filter() method, which is used when you want to extract a subset of values from the iterable. When using .filter(), remember that we are filtering in values, not filtering out. This means that each item in the iterable that evaluates true will be included in the filter.

Let’s use an example of keeping only odd integers. We’re using the modulus operator to calculate the remainder of dividing by 2. When that remainder equals 1, we know the number was odd.

const numbers = [1,2,3,4,5,6,7,8];
let odds = [];for(let i=0; i < numbers.length; i++) {
   if(numbers[i] % 2 == 1) {
      odds.push(numbers[i]);
   }
}

Similar to the .map() method, .filter() accepts a single callback to where each value in the iterable will be passed.

const numbers = [1,2,3,4,5,6,7,8];
let odds = numbers.filter(num => num % 2);

Similar rules apply for this callback. Since there’s a single input, and the body of the function is a single expression, we can omit the parameter list parentheses, the curly braces defining the body, and the return keyword.

Leave a Comment