Well, what have you got so far? Testing on cell[x].contents.length ought to be enough to test whether it 's empty or not. If so, merge with the left one and continue with the one to the right. If not, continue with the one to the right. (The pattern here is obvious.)