JS-152-Objects-Arrays
  • Introduction
  • 04-Objects
    • OOP-Basics
      • Overview
      • Coding the Example
    • Prototypes
      • Object Prototypes
      • Prototypes Continued
    • Inheritance
      • Inheritance
    • Synopsis
      • Synopsis
    • Challenges
    • Solutions
      • Constructor Function
        • Person Constructor
        • Explanation
      • Inheritance Challenge
        • Code
        • Explanation
      • Family Challenge
        • Child
        • Pet
  • 05-Arrays
    • Array Basics
      • Array Overview
      • Creating an Array
      • Individual Elements and Length
      • Iterating Over Arrays
    • Array Methods
      • Methods Overview
      • .join() Method
      • .reverse() Method
      • .split() Method
      • .replace() Method
      • .splice() Method
      • .map() Method
      • .indexOf() Method
      • .filter() Method
      • .every() Method
    • Palindrome Algorithm
    • Array Challenges
    • Solutions
      • First and Last
        • First Element
        • Last Element
      • Most Frequent
      • Largest and Smallest
        • Single Array
        • Multiple Arrays
      • Missing Number
      • "Arrays" in the DOM
      • Sorting
        • Bubble Sort
        • Selection Sort
    • Resources
Powered by GitBook
On this page
  1. 05-Arrays
  2. Array Methods

.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 ==.

Previous.indexOf() MethodNext.every() Method

Last updated 7 years ago