Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying query filters to JavaScript array of objects

Tags:

javascript

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?

like image 447
Dawn17 Avatar asked Sep 09 '19 02:09

Dawn17


People also ask

Can you use filter on an array of objects JavaScript?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.


1 Answers

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))
              )
        ) 
    )
like image 63
Nikhil Avatar answered Oct 17 '22 15:10

Nikhil