How to filter a Javascript array with a condition

Description

filter() accepts two arguments:

  • a function to run on each item and
  • an optional scope object

filter() runs the given function on every item and returns an array of all items for which the function returns true.

The function passed in receives three arguments:

  • the array item value,
  • the position of the item in the array
  • the array object itself.

Example

For example, to return an array of all numbers greater than 2:


var numbers = [1,2,3,4,5,4,3,2,1]; 
        //w w  w . j  a  va 2  s  .com
var filterResult = numbers.filter(function(item, index, array){ 
   return (item > 2); 
}); 
console.log(filterResult); //[3,4,5,4,3] 

filter() does not change the values contained in the array.

The code above generates the following result.





















Home »
  Javascript »
    Javascript Reference »




Array
Canvas Context
CSSStyleDeclaration
CSSStyleSheet
Date
Document
Event
Global
History
HTMLElement
Input Element
Location
Math
Number
String
Window