The filter() Array function takes an existing array and generates a new array with entries that meet a set of criteria. We will look at how to utilize the JavaScript filter array function in this tutorial.
array.filter(function(value, index, arr), thisValue)
Parameter | Description |
---|---|
function() | For each array element, a function must be executed. |
currentValue | This is the current elements value. |
index | The current elements index number. |
arr | This is the current elements array. |
thisValue | A value that will be used by the function. The default value is undefined. |
Lets see an example of a filter where we only display numbers greater than 5 in a given array
let numbers = [10,30,-35,2,4,7];
let array = numbers.filter(function(value) {
return value > 5; });
console.log(array);
[ 10, 30, 7 ]
Lets see how we can use the filter() method in objects.
let colors_array = [{value: "blue"},
{value: "green"},
{value:"yellow"}];
let select_color = colors_array.filter(function(color) {
return color.value !== "green"; });
console.log(select_color);
[ { value: 'blue' }, { value: 'yellow' } ]