Refactoring: simplify and optimize code by avoiding toArray
Add test for issue #2430