English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JavaScript Array filter() Method

 JavaScript Array Object

 The filter() method creates a new array containing all elements that pass the test implemented by the provided callback function.

Note: The filter() method does not change the original array.

Syntax:

array.filter(callback, thisArg)
var age = [1, 30, 39, 29, 10, 13];
var val = age.filter(isAdult);
function isAdult(element) {
    return element >= 18;
}
Test and see‹/›

Browser Compatibility

The numbers in the table specify the first browser version that fully supports the filter() method:

Method
filter()Is1.5IsIs9

Parameter value

ParameterDescription
callback
The function to be executed for each element in the array.
Function parameters:
  • element(Required)-The current element being processed in the array

  • index(Optional)-The index of the current element being processed in the array

  • array(Optional)- Called arrayFilter

thisArg(Optional) Value, used when executing the callback

Technical Details

Return Value:A new array with elements that pass the test. If no elements pass the test, an empty array will be returned
JavaScript Version:ECMAScript 5

More Examples

The following example uses the filter() method to filter array content based on search conditions:

var fruits = ['apple', 'mango', 'banana', 'orange', 'grapes'];
/**
 * Array Filter Options Based on Search Conditions (Query)
 */
function filterItems(query) {
   return fruits.filter(function(el) {
         return el.indexOf(query) > -1;
   }
}
function myFunc(val) {
    document.getElementById("result").innerHTML = filterItems(val);
}
Test and see‹/›

 JavaScript Array Object