5
const sample_table1_data = [
    { title: 'aa-1', customers: ['a', 'b']},
    { title: 'aa-2', customers: ['a', 'c']},
    { title: 'bb-1', customers: ['d', 'e']},
    { title: 'cc-1', customers: ['b', 'e', 'f']},
    { title: 'dd-1', customers: ['f', 'g']},
    { title: 'dd-2', customers: ['g']},

]

I am trying to filter the array of objects that looks like above. Let's say I give queries for both title which is a string and customer which is an array of strings.

I made a function named filterData which takes an object that looks like

let filter_info = {
    title: ['aa, cc'], customer: ['b']
}

I want the function to filter out the objects that have aa in the title and b in the customers, expecting the output to be

output = [
    { title: 'aa-1', customers: ['a', 'b']},
    { title: 'cc-1', customers: ['b', 'e', 'f']},
]

because these are the two objects that satisfy the queries (title that includes aa and cc AND customers include 'b')

I tried

filterData = (filters) => {
    let title_filter = filters.title
    let customer_filter = filters.customer
    const myItems = this.state.table1_data

    const keywordsToFindLower = title_filter.map(s => s.toLowerCase());
    const customerKeywords = customer_filter.map(s => s.toLowerCase())

    // filters the profile data based on the input query (selected option)
    const newArray = myItems.filter(item =>
        keywordsToFindLower.some(
            title_filter => (item.title.toLowerCase()).includes(title_filter)
        ) 
        &&
        customerKeywords.some(
            customer_filter => (item.customers.toLowerCase()).includes(customer_filter)
        ) 
    )
}

However, this gives me an error since customers is an array, not a string.

What is the correct usage if I want to achieve this task?

0

1 Answer 1

7

You are almost there. You can use Array.some() on customers array in the filter method like this:

item.customers.some(value => value.toLowerCase().includes(customer_filter))

Then your filter method would look like:

const newArray = myItems.filter(item =>
        keywordsToFindLower.some(
            title_filter => (item.title.toLowerCase()).includes(title_filter)
        ) 
        &&
        customerKeywords.some(
            customer_filter =>
              (item.customers.some(
                 value => value.toLowerCase().includes(customer_filter))
              )
        ) 
    )
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.