English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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.
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‹/›
The numbers in the table specify the first browser version that fully supports the filter() method:
Method | |||||
filter() | Is | 1.5 | Is | Is | 9 |
Parameter | Description |
---|---|
callback | The function to be executed for each element in the array. Function parameters:
|
thisArg | (Optional) Value, used when executing the callback |
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 |
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‹/›