我有一个根据键值排序的国家/地区列表数组对象,其中键是字母。我有所有字母表列表的一部分用于导航。一旦用户单击任何字母,字母内容应滚动到该字母。或者,如果该键没有值,它应该滚动到最近的有值的键。
例如:有些键如 H、I、J、K、Q 在国家/地区数组中没有值。 因此,一旦我单击“I”键,它应该滚动到最近具有值的键,即:G 我如何从字母表数组中检查并选择最近的键,一旦用户选择任何键,该键就具有价值。
const countryArray = [
{ key: 'A', value: ['Albania', 'Algeria'] },
{ key: 'B', value: ['Belgium', 'Brazil'] },
{ key: 'C', value: [] }, // No value
// ... other keys
{ key: 'G', value: ['Germany', 'Greece'] },
{ key: 'H', value: [] }, // No value
// ... more keys
{ key: 'Z', value: ['Zambia', 'Zimbabwe'] }
];
function findNearestKeyWithValue(key) {
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const keyIndex = alphabet.indexOf(key);
// Check to the left and right for the nearest key with value
for (let offset = 0; offset < alphabet.length; offset++) {
const leftIndex = keyIndex - offset;
const rightIndex = keyIndex + offset;
if (leftIndex >= 0 && countryArray[leftIndex] && countryArray[leftIndex].value.length > 0) {
return countryArray[leftIndex].key;
}
if (rightIndex < alphabet.length && countryArray[rightIndex] && countryArray[rightIndex].value.length > 0) {
return countryArray[rightIndex].key;
}
}
// Default to first key if no key with value is found
return countryArray[0].key;
}
function scrollToCountry(key) {
const nearestKey = findNearestKeyWithValue(key);
const element = document.getElementById(nearestKey);
if (element) {
element.scrollIntoView({ behavior: 'smooth' });
}
}
<div id="alphabetNav">
<span onclick="scrollToCountry('A')">A</span>
<span onclick="scrollToCountry('B')">B</span>
<span onclick="scrollToCountry('C')">C</span>
<!-- ... other alphabet letters -->
<span onclick="scrollToCountry('Z')">Z</span>
</div>
<div id="countryList">
<!-- Each key will have a corresponding div with an id -->
<div id="A">Albania, Algeria</div>
<div id="B">Belgium, Brazil</div>
<!-- ... other countries -->
<div id="G">Germany, Greece</div>
<div id="Z">Zambia, Zimbabwe</div>
</div>