Middle+
//Implement a sorted list of cities // Example: // A // Arkhangelsk // Astrakhan // B // Belgorod // ...
sobes.tech AI
Answer from AI
To implement a sorted list of cities grouped by the first letter, you can use the following approach:
- Sort the array of cities alphabetically.
- Iterate through the sorted list and group cities by their first letter.
- Display the letter and the corresponding cities.
Example in JavaScript:
const cities = ["Arkhangelsk", "Astrakhan", "Belgorod", "Bryansk", "Vladivostok"];
// Sort the cities
cities.sort((a, b) => a.localeCompare(b, 'ru'));
// Group by the first letter
const grouped = cities.reduce((acc, city) => {
const firstLetter = city[0].toUpperCase();
if (!acc[firstLetter]) {
acc[firstLetter] = [];
}
acc[firstLetter].push(city);
return acc;
}, {});
// Output the result
for (const letter of Object.keys(grouped).sort()) {
console.log(letter);
grouped[letter].forEach(city => console.log(city));
}
Output:
A
Arkhangelsk
Astrakhan
B
Belgorod
Bryansk
V
Vladivostok
This approach is easily scalable and supports any set of cities.