Почему не сортируется массив arrBySelect по клику на ? Как исправить?
select.onchange = function createTBody(){
message.style = 'display: none';
theadtr.innerHTML = `<th class="th">Country name</th>
<th>Capital</th>
<th>World region</th>
<th>Languages</th>
<th class="th">Area</th>
<th>Flag</th>`
let arrBySelect;
let selectValue = select.value;
langArr.forEach( function(lang) {
if (lang === selectValue) {
arrBySelect = externalService.getCountryListByLanguage(selectValue)
}
})
regArr.forEach( function(reg) {
if (reg === selectValue) {
arrBySelect = externalService.getCountryListByRegion(selectValue)
}
})
let th = document.querySelectorAll('.th')
th.forEach(th => th.addEventListener('click', (e) => {
if(e.target.classList.contains('th')) {
th.classList.remove('th')
th.classList.add('thReverse')
console.log(arrBySelect)
arrBySelect.sort((a, b) => b > a ? 1 : -1);
} else {
th.classList.remove('thReverse')
th.classList.add('th')
arrBySelect.sort((a, b) => a > b ? 1 : -1)
}
}))
tbody.innerHTML = arrBySelect.map((country) =>
` <tr>
<td>${country.name}</td>
<td>${country.capital}</td>
<td>${country.region}</td>
<td>${getLanguages(country.languages)}</td>
<td>${country.area}</td>
<td><img src="${country.flagURL}"></td>
</tr> `
).join('')
}
```
Ответы (1 шт):
Автор решения: Igor
У Вас в массиве - набор объектов-стран, что Вы тут b < a ? сравниваете?
theadtr.innerHTML = `<th class="th" data-sortfield="name">Country name</th> ...`
...
b[th.dataset.sortfield] < a[th.dataset.sortfield] ? ...
→ Ссылка
select.onchange = function createTBody(){
message.style = 'display: none';
theadtr.innerHTML = `<th class="th">Country name</th>
<th>Capital</th>
<th>World region</th>
<th>Languages</th>
<th class="th">Area</th>
<th>Flag</th>`
let arrBySelect;
let selectValue = select.value;
langArr.forEach( function(lang) {
if (lang === selectValue) {
arrBySelect = externalService.getCountryListByLanguage(selectValue)
}
})
regArr.forEach( function(reg) {
if (reg === selectValue) {
arrBySelect = externalService.getCountryListByRegion(selectValue)
}
})
let th = document.querySelectorAll('.th')
th.forEach(th => th.addEventListener('click', (e) => {
if(e.target.classList.contains('th')) {
th.classList.remove('th')
th.classList.add('thReverse')
console.log(arrBySelect)
arrBySelect.sort((a, b) => b > a ? 1 : -1);
} else {
th.classList.remove('thReverse')
th.classList.add('th')
arrBySelect.sort((a, b) => a > b ? 1 : -1)
}
}))
tbody.innerHTML = arrBySelect.map((country) =>
` <tr>
<td>${country.name}</td>
<td>${country.capital}</td>
<td>${country.region}</td>
<td>${getLanguages(country.languages)}</td>
<td>${country.area}</td>
<td><img src="${country.flagURL}"></td>
</tr> `
).join('')
}
```
Ответы (1 шт):
Автор решения: Igor
→ Ссылка
У Вас в массиве - набор объектов-стран, что Вы тут b < a ? сравниваете?
theadtr.innerHTML = `<th class="th" data-sortfield="name">Country name</th> ...`
...
b[th.dataset.sortfield] < a[th.dataset.sortfield] ? ...