.filter() Method

Use the .filter() method to filter out certain elements. In this example we're going to filter even numbers.

var numbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
var even = numbers.filter(function(item) {
  if(item % 2 == 0){
    return true;
  } else {
    return false;
  }
});

console.log(even);

Output

[ 2, 4, 6, 8, 10 ]

In our function we used the remainder operator %. So, if any element is divisible by two, it is considered even. Otherwise we filter it out. You could similarly filter odd numbers by adding an exclamation point before the ==.

Last updated