I am trying to filter an array by keyword and category vanilla js

Viewed 82

I have an array with multiple objects that I wish to filter by category -- income or expense -- and by typing keywords inside a search input(description).

This is an example of what the objects look like inside of the array mentioned above:

Entry {amount: 1500, category: "salary", date: "2022-07-27", description: "main income", iconCategory: "fa-money-bill", iconType: "fa-arrow-up-right" type: "income"}

I have created another object with all the filters Im going to use:

let filters = {
description: "",
type: "income"}

Here are the two functions that filter both of the criterias mentioned:

   const searchDescription = (keyword, array) =>{
        return array.filter(el => el.description.toLowerCase().includes(keyword))
    }
    const selectType = (option, array) =>{
        return array.filter(el => el.type.toLowerCase().includes(option))
    }

The function below is what prints the data on the table when the event listener select option is clicked or when the user types somenthing on the description input:

const printData = () =>{
tableContent.innerHTML = "";
let filter =   searchDescription(filters.description, classInstance)
filter = selectType(filters.type, classInstance)
filter.map(el =>{
    tableContent.innerHTML += `
    <tr class="tr__styles" data-groups="${el.type === 'income'? "['income','all']" : "['expenses','all;]"}">
    <td><i class="fa-solid ${el.iconType} ${el.type === "income"? "icon__color2" : "icon__color"}"></i></td>
    <td>
        <i class="fa-solid ${el.iconCategory} iconBackground__circle table__icons"></i>
        ${el.category}
    </td>
    <td>${el.description}</td>
    <td class="${el.type === 'income'? 'positive__amount' : ''}">${el.type === 'income'? '+' : '-'} $${el.amount}</td>
    <td>${el.date}</td>
    <td>
        <button class="table__buttons"><i class="fa-solid fa-pencil"></i></button>
        <button class="table__buttons"><i class="fa-solid fa-trash-can"></i></button>
    </td>
    </tr>
    `
})}

These are the event listeners that trigger each event:

filterByDescriptionInput.addEventListener("keyup", e =>{
    filters.description = e.target.value;
    console.log(filters.description)
    return printData()
})

filterByEntryTypeBtn.addEventListener("change", e =>{
    console.log(e.target.value)
    filters.type = e.target.value;
    return printData()
})

When I click on my filterByEntryTypeBtn and toggle between "income" or "expense" it shows me the correct data however, when I try to use the search bar, it doesn't work at all. Also, I dont know how to make a default state that shows the array in its pure state without filtering as soon as the page loads.

0 Answers
Related