Javascript Reference - How to filter a Javascript array with a condition








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]; 
        
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.