More efficient implementation using filter, reduceFunction, and map