merged matehat's toArray patch
(cherry picked from commit 67f1e8a9c89f644ee54be215146742a1b3174b31)