As you can imagine, this situation has emerged numerous times during the time of the Prophet ﷺ. While right after hijra, there was only one masjid, and the Prophet ﷺ was the imam, as Islam spread across Medina, multiple masjids emerged with multiple imams. There were also situations of who leads the prayers while traveling, or while in a group that cannot join the main masjids.
عَنْ أَبِي مَسْعُودٍ الأَنْصَارِيِّ، قَالَ قَالَ رَسُولُ اللَّهِ صلى الله عليه وسلم: يَؤُمُّ الْقَوْمَ أَقْرَؤُهُمْ لِكِتَابِ اللَّهِ فَإِنْ كَانُوا فِي الْقِرَاءَةِ سَوَاءً فَأَعْلَمُهُمْ بِالسُّنَّةِ فَإِنْ كَانُوا فِي السُّنَّةِ سَوَاءً فَأَقْدَمُهُمْ هِجْرَةً فَإِنْ كَانُوا فِي الْهِجْرَةِ سَوَاءً فَأَقْدَمُهُمْ سِلْمًا وَلاَ يَؤُمَّنَّ الرَّجُلُ الرَّجُلَ فِي سُلْطَانِهِ وَلاَ يَقْعُدْ فِي بَيْتِهِ عَلَى تَكْرِمَتِهِ إِلاَّ بِإِذْنِهِ
Abu Mas'ud al-Ansari reported Allah's Messenger (ﷺ) as saying: The one who is most versed in Allah's Book should act as Imam for the people, but If they are equally versed in reciting it, then the one who has most knowledge regarding Sunnah if they are equal regarding the Sunnah, then the earliest one to emigrate; it they emigrated at the same time, then the earliest one to embrace Islam. No man must lead another in prayer where (the latter) has authority, or sit in his place of honour in his house, without his permission. Ashajj in his narration used the word, "age" in place of "Islam".
— Sahih Muslim 673 a
The Prophet ﷺ laid out the criteria in order:
- Most versed in the Qrr'an
- Most knowledgeable about sunnah
- Earliest to emigrate (not applicable nowadays)
- Earliest to embrace Islam
- Eldest.
Malikis and Shafi'is understanding of the most versed in Qur'an as being the most knowledgable about its rulings (jurisprudence) as well as about reading it (recitation).They base this on the fact that the Prophet ﷺ during his last illness, he appointed Abu Bakr to lead the prayers in his place while the top reciter was Ubay ibn Ka'b (see Sunan Ibn Majah, Vol. 1, Book 1, Hadith 154).
In practice nowadays, imams are appointed by a local authority (government, society, community, etc.) as a permanent imam (Arabic: إمام راتب), using all sorts of different processes other than the one laid out by the Prophet ﷺ; too many and too varied to be able to compile, and none that I am aware of that has an Islamic basis.