filter() – filters elements that pass a test
Array.filter() function is used to filter elements in this array based on a filtering function.
Syntax
array.filter( function, thisValue )
array
is the given array.every
is inbuilt array method name.function
a function to run for every element. the definition of the function isfunction(element, index, arr)
. the function must return a boolean value oftrue
orfalse
.element
is the current element in the array.index
of the current element [optional argument].arr
is the array of current element [optional argument].
thisValue
is a value passed to the function as its this value [optional argument].
filter()
method creates and returns a new array with the elements from the original array that return true
for the given function
.
Examples
1. Filter even numbers from the given numeric array nums
.
function isEven(num) {
if (num % 2 == 0) {
return true;
} else {
return false;
}
}
nums = [4, 1, 8, 0, 2, 3, 5];
evenNumbers = nums.filter(isEven);
console.log(evenNumbers);
2. Filter non-empty strings from the given string array names
.
function isNonEmptyString(item) {
if (item.length !== 0) {
return true;
} else {
return false;
}
}
names = ["apple", "banana", "", "cherry", "", "mango"];
nonEmptyNames = names.filter(isNonEmptyString);
console.log(nonEmptyNames);