first version of a general function to group array elements