filter method
The filter
method allows you
to filter the elements of an array,
leaving only elements that match
a certain condition. The method in
the parameter receives a function
that will be executed for each
element of the array. As its result,
the method returns a new array,
which will include only those elements
for which the passed function returns
true
.
You can pass three parameters to a function. If these parameters are present (they are not required), then the first one will automatically get the array element, the second one will get its number in the array (index), and the third one will get the array itself.
Syntax
let new array = array.filter(function(element, index, array) {
some code
return true or false
});
Example
Let's filter an array, leaving only positive numbers in it:
let arr = [-2, 5, 1, -5, -1, 1, 3, 4, -1];
let res = arr.filter(function(elem) {
if (elem >= 0) {
return true;
} else {
return false;
}
});
console.log(res);
The code execution result:
[5, 1, 1, 3, 4]
Example
We shorten a code using arrow function:
let arr = [-2, 5, 1, -5, -1, 1, 3, 4, -1];
let res = arr.filter(elem => {
if (elem >= 0) {
return true;
} else {
return false;
}
});
console.log(res);
The code execution result:
[5, 1, 1, 3, 4]
Example
Let's shorten a code using shorthand for logical operations:
let arr = [-2, 5, 1, -5, -1, 1, 3, 4, -1];
let res = arr.filter(elem => {
return elem >= 0;
});
console.log(res);
The code execution result:
[5, 1, 1, 3, 4]
Example
Let's shorten a code using the features of arrow functions:
let arr = [-2, 5, 1, -5, -1, 1, 3, 4, -1];
let res = arr.filter(elem => elem > 0);
console.log(res);
The code execution result:
[5, 1, 1, 3, 4]
Example
If necessary, an array itself can be passed to the third parameter:
let res = arr.filter(function(elem, index, arr) {
array arr will be available here
});