Фильтрация по выбранным checkbox
const services = [{
id: 1,
Type: "Apple",
Size: "L",
Color: "Red"
},
{
id: 2,
Type: "Apple",
Size: "S",
Color: "Black"
},
{
id: 3,
Type: "Window",
Size: "M",
Color: "Black"
},
{
id: 4,
Type: "Linux",
Size: "M",
Color: "White"
},
{
id: 5,
Type: "Linux",
Size: "S",
Color: "Red"
},
{
id: 6,
Type: "Windows",
Size: "S",
Color: "Red"
},
]
<form id="form">
Выберите продукты:
<div>
<p>Type</p>
<input id="apple" type="checkbox" name="Type-Apple">
<label for="apple">Apple</label> <br>
<input id="window" type="checkbox" name="Type-Window">
<label for="window">Window</label> <br>
<input id="linux" type="checkbox" name="Type-Linux">
<label for="linux">Linux</label> <br>
</div>
<div>
<p>Size</p>
<input id="size-s" type="checkbox" name="Size-S">
<label for="size-s">S</label> <br>
<input id="size-m" type="checkbox" name="Size-M">
<label for="size-m">M</label> <br>
<input id="size-l" type="checkbox" name="Size-L">
<label for="size-l">L</label> <br>
</div>
<div>
<p>Color</p>
<input id="color-black" type="checkbox" name="Color-Black">
<label for="color-black">Black</label> <br>
<input id="color-red" type="checkbox" name="Color-Red">
<label for="color-red">Red</label> <br>
<input id="color-white" type="checkbox" name="Color-White">
<label for="color-white">White</label> <br>
</div>
</form>
<br>
<div>
Выбранные продукты:
</div>
Ответы (2 шт):
Автор решения: EzioMercer
→ Ссылка
Можете попробовать такой вариант (лучше будет, если открыть на полный экран):
const services = [{
id: 1,
Type: "Apple",
Size: "L",
Color: "Red"
},
{
id: 2,
Type: "Apple",
Size: "S",
Color: "Black"
},
{
id: 3,
Type: "Window",
Size: "M",
Color: "Black"
},
{
id: 4,
Type: "Linux",
Size: "M",
Color: "White"
},
{
id: 5,
Type: "Linux",
Size: "S",
Color: "Red"
},
{
id: 6,
Type: "Windows",
Size: "S",
Color: "Red"
},
]
const findServices = (filters) => {
let answer = [...services];
for (const filter in filters) {
const filterSet = filters[filter];
answer = answer.filter(
item => filterSet.size === 0 || filterSet.has(item[filter])
);
}
document.querySelector('#selected').innerHTML = answer.map(item => `<p>${item.Type} ${item.Size} ${item.Color}</p>`).join('');
return answer;
}
const checkboxes = document.querySelectorAll('#form [type="checkbox"]');
const filters = {
Type: new Set(),
Size: new Set(),
Color: new Set(),
};
checkboxes.forEach(checkbox => {
checkbox.addEventListener('change', (e) => {
console.clear();
const target = e.target;
const [prop, value] = target.name.split('-');
filters[prop][target.checked ? 'add' : 'delete']('' + value);
findServices(filters);
})
})
document.onload = findServices(filters);
#main {
display: flex;
width: 64%;
justify-content: space-between;
}
<div id="main">
<form id="form">
Выберите продукты:
<div>
<p>Type</p>
<input id="apple" type="checkbox" name="Type-Apple">
<label for="apple">Apple</label> <br>
<input id="window" type="checkbox" name="Type-Window">
<label for="window">Window</label> <br>
<input id="linux" type="checkbox" name="Type-Linux">
<label for="linux">Linux</label> <br>
</div>
<div>
<p>Size</p>
<input id="size-s" type="checkbox" name="Size-S">
<label for="size-s">S</label> <br>
<input id="size-m" type="checkbox" name="Size-M">
<label for="size-m">M</label> <br>
<input id="size-l" type="checkbox" name="Size-L">
<label for="size-l">L</label> <br>
</div>
<div>
<p>Color</p>
<input id="color-black" type="checkbox" name="Color-Black">
<label for="color-black">Black</label> <br>
<input id="color-red" type="checkbox" name="Color-Red">
<label for="color-red">Red</label> <br>
<input id="color-white" type="checkbox" name="Color-White">
<label for="color-white">White</label> <br>
</div>
</form>
<br>
<div>
Выбранные продукты:
<div id="selected"></div>
</div>
</div>
Автор решения: novvember
→ Ссылка
Мой вариант:
- Проходим исходный массив массивов
- В каждом из них проходим искомый массив: все ли элементы есть
- Если да, добавляем этот массив в результат
const array1 = [
['apple', 'windows', 'linux'],
['iphone', 'android'],
['apple', 'windows']
];
function findArrayInArrayOfArrays (originalArrays, targetArray) {
// Оставляем в новом массиве только те массивы, в которых есть искомые значения
const resultArray = originalArrays.filter( originalArray => {
// Проверяем, что все искомые значения есть в массиве
return targetArray.reduce( (isValid, targetValue) => {
if ( isValid === true && originalArray.includes(targetValue) ) {
return true;
} else {
return false;
}
}, true);
});
// По условиям задачи разные варианты того, что возвращает функция
if ( resultArray.length === 0 ) return false;
if ( resultArray.length === 1 ) return resultArray[0];
return resultArray;
}
console.log( findArrayInArrayOfArrays (array1, ['apple', 'linux']) ) // Одно совпадение: ['apple', 'windows', 'linux']
console.log( findArrayInArrayOfArrays (array1, ['apple', 'linux', 10]) ) // Нет совпадений
console.log( findArrayInArrayOfArrays (array1, ['apple']) ) // Более одного совпадения