JSFiddle - React, Tailwind, and code Playground
by kirito0709
HTML
<select id="city-filter">
<option value="">- Выберите город -</option>
<option value="moscow">Москва</option>
<option value="stpetersburg">Санкт-Петербург</option>
<option value="novosibirsk">Новосибирск</option>
</select>
<select id="brand-filter">
<option value="">- Выберите бренд -</option>
<option value="brand1">Бренд 1</option>
<option value="brand2">Бренд 2</option>
<option value="brand3">Бренд 3</option>
</select>
<select id="direction-filter">
<option value="">- Выберите направление -</option>
<option value="direction1">Направление 1</option>
<option value="direction2">Направление 2</option>
<option value="direction3">Направление 3</option>
</select>
<select id="format-filter">
<option value="">- Выберите формат -</option>
<option value="format1">Формат 1</option>
<option value="format2">Формат 2</option>
<option value="format3">Формат 3</option>
</select>
JavaScript
const events = [
{city: "moscow", brand: "brand1", direction: "direction1", format: "format1"},
{city: "stpetersburg", brand: "brand1", direction: "direction2", format: "format2"},
{city: "moscow", brand: "brand2", direction: "direction1", format: "format3"},
{city: "novosibirsk", brand: "brand3", direction: "direction3", format: "format1"},
];
const filters = {
city: '',
brand: '',
direction: '',
format: '',
};
const filterEvents = () => {
let filteredEvents = events;
for (const key in filters) {
if (filters[key]) {
filteredEvents = filteredEvents.filter(event => event[key] === filters[key]);
}
}
return filteredEvents;
};
document.querySelectorAll('select').forEach(select => {
select.addEventListener('change', () => {
filters[select.id.split('-')[0]] = select.value;
const filteredEvents = filterEvents();
// блокируем недоступные варианты для уже выбранных фильтров
document.querySelectorAll('select').forEach(select => {
const key = select.id.split('-')[0];
select.querySelectorAll('option').forEach(option => {
if (option.value) {
const tempFilters = {...filters, [key]: option.value};
const tempFilteredEvents = events.filter(event => {
for (const tempKey in tempFilters) {
if (tempFilters[tempKey] && event[tempKey] !== tempFilters[tempKey]) {
return false;
}
}
return true;
});
option.disabled = !tempFilteredEvents.length;
}
});
});
console.log(filteredEvents);
console.log(filters);
});
});