Replaced for loops with filter function