merge and sort arrays according to array structure