We present a self-organizing model of group formation in three-dimensional space, and use it to investigate the spatial dynamics of animal groups such as fish schools and bird flocks. We reveal the existence of major group-level behavioural transitions related to minor changes in individual-level interactions. Further, we present the first evidence for collective memory in such animal groups (where the previous history of group structure influences the collective behaviour exhibited as individual interactions change) during the transition of a group from one type of collective behaviour to another. The model is then used to show how differences among individuals influence group structure, and how individuals employing simple, local rules of thumb, can accurately change their spatial position within a group (e.g. to move to the centre, the front, or the periphery) in the absence of information on their current position within the group as a whole. These results are considered in the context of the evolution and ecological importance of animal groups.