The second-order (v22) and third-order (v33) Fourier coefficients describing the azimuthal anisotropy of prompt and nonprompt (from b-hadron decays) J/ψ, as well as prompt ψ(2S) mesons are measured in lead-lead collisions at a center-of-mass energy per nucleon pair of sNNsNN = 5.02 TeV. The analysis uses a data set corresponding to an integrated luminosity of 1.61 nb−1−1 recorded with the CMS detector. The J/ψ and ψ(2S) mesons are reconstructed using their dimuon decay channel. The v22 and v33 coefficients are extracted using the scalar product method and studied as functions of meson transverse momentum and collision centrality. The measured v22 values for prompt J/ψ mesons are found to be larger than those for nonprompt J/ψ mesons. The prompt J/ψ v22 values at high pTT are found to be underpredicted by a model incorporating only parton energy loss effects in a quark-gluon plasma medium. Prompt and nonprompt J/ψ meson v33 and prompt ψ(2S) v22 and v33 values are also reported for the first time, providing new information about heavy quark interactions in the hot and dense medium created in heavy ion collisions.