Flatten an array with a custom function