JavaScript filter()
eliminating elements of an array that do not meet a condition
Motivation
Suppose we have an array and we wish to go through its elements, then perform remove elements that do not satisfy some condition...
We could use the built-in filter()
function to iterate and eliminate:
Addition
In addition to the current element of the iteration, the filter
method also has two optional parameters:
the
index
of the current elementthe original
array
showing all the elements
For example, we could provide more detail to the message logged to the console:
Here we have to include the return
statement because we have more than one line in the function!
Logging the original grades array only in the first iteration with that if
statement, this will log:
Summary
Remember that filter()
:
returns the values into a new array
the length of this array will always be equal or less than the original array
does not modify the original array
Last updated