JSFiddle - React, Tailwind, and code Playground
HTML
<div id="match">Matching against <span id="filter"></span></div>
<div id="results"></div>
CSS
#match {
margin: 10px 0;
}
table {
border-collapse: collapse;
border: 1px solid navy;
}
td {
padding: 10px;
+ td {
border-left: 1px solid navy;
}
}
tr:first-of-type {
background: hsl(200, 50%, 70%);
font-weight: bold;
text-transform: uppercase;
letter-spacing: 1px;
}
tr:nth-of-type(2n + 3) {
background: hsl(200, 50%, 95%);
}
body {
font-family: sans-serif;
}
JavaScript
const filters = { race: ["human", "fae"], class: "cleric" };
function hasItemInBothArrays(targetArray, searchArray) {
const matches = targetArray.some((value) => searchArray.includes(value));
console.log(targetArray, searchArray, matches);
return matches;
}
function getFilteredCards() {
const searchFilters = new Map(Object.entries(filters));
const filterScore = searchFilters.size;
const cards = [
{
id: "A",
score: 0,
matches: false,
filters: { race: "human", class: ["cleric", "paladin"] }
},
{
id: "B",
score: 0,
matches: false,
filters: { race: "human", class: "paladin" }
},
{
id: "C",
score: 0,
matches: false,
filters: { race: ["human", "fae"], class: "cleric" }
},
{
id: "D",
score: 0,
matches: false,
filters: { race: "shapeshifter", class: "druid" }
},
{
id: "E",
score: 0,
matches: false,
filters: { race: "fae", class: "druid" }
},
{
id: "F",
score: 0,
matches: false,
filters: { race: "elemental", class: "cleric" }
}
];
searchFilters.forEach((value, key) => {
cards.forEach((card) => {
const matchesFilter = hasItemInBothArrays(
[card.filters[key]].flat(),
[value].flat()
);
if (matchesFilter) card.score += 1;
if (card.score === filterScore) card.matches = true;
});
});
return cards;
}
function printResult() {
const results = getFilteredCards();
const table = document.createElement("table");
// get headers
const headers = table.insertRow(0);
for (const key in results[0]) {
const cell = headers.insertCell(-1);
cell.innerHTML = key;
}
// fill data
results.forEach((result) => {
const row = table.insertRow(-1);
for (const key in result) {
const cell = row.insertCell(-1);
cell.innerHTML = JSON.stringify(result[key]);
}
});
...