Filtering arrays with complex conditions