Well, it does iterate six times, but not necessarily on the whole initial array. Each time it is filtered it becomes smaller. It would be more effective to have one filter method, but the difference might not be as great as you expect.
If you still want to use this solution, you can increase the performance by using the most selective (that is the filter that is expected filter out the most) first. That way, the following arrays will be smaller and there will be less to iterate through.
As @Redu points out (in comments) you can chain your filters using the ||
operator. This will make sure you only do one iteration.
The reason behind this is that Array.prototype.filter
returns a new array. Compare this with the Java Stream
API, that returns a stream, and thus can go "depth first" through the call list. The down side of this is that you need a terminal operation in the end, to "collect" your result.
In javascript
rawArray.filter(x)
iterates the rawArray
and returns a new filtered array - which can in turn be filtered, or used as it is. It will result in a call to x
for each of the elements in rawArray
.
In Java the equivalent would be
rawArray.stream().filter(x)
which would actually not do anything at all at this point. No calls to x
would be done. The return value would be a Stream
, that can be used later. It can be further filtered, but it is not until the values are collected in some way - with a terminal operation - that calls are made.
Lets compare javascript
rawArray.filter(x).filter(y).length
to Java
rawArray.stream().filter(x).filter(y).count()
In javascript, this would first iterate over all of the elements of rawArray
, calling x
for each of them, and store the result in an intermediate array. Then the javascript engine would iterate over all of the elements of the intermediate array, calling y
for each element, and store the result in a second intermediate array, which it would then check the size of.
In Java, the snippet would result in the VM iterating over the elements of rawArray
, first calling x
, and, if x
is true
, then calling y
on each element, and, if still true
incrementing the counter. There would be no intermediate arrays, and only one iteration over the dataset.
Functional programming is interesting, and when used properly, it creates less code that is less complex and ideally perhaps even a bit easier to read, but it does hand over a lot of responsibility to the framework (or engine or VM or whatever), and it is important to realize that seemingly similar code, while behaving similarly, can perform vastly differently in different environments.
||
operator to chain up all thoseremoveXX
functions in a single filter.||
operator would not invoke the remaining checks once it meets atrue
value and this will save a lot of redundant function calls.||
operator was used.