I'm quite a beginner in Javascript and I'm french. I have a project and it's goal is to filter by tags some cooking recipes (french words but don't worry). So my aim is to click on an ingredient (like "Sugar" or "Sucre"), and it's suppose to filter every recipe from an array that includes this ingredient by creating a tag.
Here's my function to create a tag :
export function createIngTag(label, dataProperty, id) {
const div = document.createElement("div")
div.setAttribute("class", "tag")
div.classList.add("ing-tag")
div.setAttribute("data-property", dataProperty)
div.setAttribute("id", id)
const span = document.createElement("span")
span.setAttribute("class", "tag-span")
span.innerHTML = label
const closeBtn = document.createElement("i")
closeBtn.classList.add("far")
closeBtn.classList.add("fa-times-circle")
closeBtn.classList.add("close-button")
closeBtn.setAttribute("data-item", label)
closeBtn.addEventListener("click", closeTag)
function closeTag(e) {
const value = e.target.getAttribute("data-item")
const index = tagsArray.findIndex((div) => div.getAttribute("data-property").toLowerCase() === value.toLowerCase());
console.log(index)
if (index === -1) {
return alert("NOT FOUND")
}
tagsArray.splice(index, 1)
console.log(tagsArray)
selectedRecipesArray.prop = [...recipes]
tagsArray.forEach((tag) => {
selectedRecipesArray.prop = filterByTags(selectedRecipesArray, tag);
console.log(selectedRecipesArray.prop)
});
closeBtn.parentElement.remove()
changeRecipesSection()
displayRecipes(selectedRecipesArray)
}
tagsSpace.appendChild(div)
div.appendChild(span)
div.appendChild(closeBtn)
tagsArray.push(div)
console.log(tagsArray)
return div
}
And here is my listener for each ingredient you click on, which is also part of my ingredient list factory :
div.addEventListener("click", () => {
if (!document.getElementById(span.textContent)) {
createIngTag(span.textContent, span.textContent, span.textContent)
tagsArray.forEach((tag) => {
selectedRecipesArray.prop = [...recipes]
selectedRecipesArray.prop = filterByTags(selectedRecipesArray, tag);
console.log(selectedRecipesArray.prop)
});
changeRecipesSection()
console.log(selectedRecipesArray.prop)
displayRecipes(selectedRecipesArray.prop)
}
})
At last, here is my function filterByTags that allows, once the tag is created to set a list of recipes supposed to match with the tag created :
export function filterByTags(recipesArr, tag) {
const result = recipesArr.filter((object) => object.ingredients.some((ingObj) =>
ingObj.ingredient.toLowerCase().includes(tag.dataset.property.toLowerCase())
));
return result;
}
Here is the problem : the filter works very well with some ingredients like Sugar, Flour, Eggs, Butter (in french : Sucre, Farine, Oeufs, Beurre) but it doesn't work with most of the ingredients from the list, the returned Array is empty. Can you help me with that ?
Here's the link to my repo : https://github.com/Romain-6793/RomainClaudot_7_30052022
thanks in advance.