Search code examples
javascriptrethinkdb

get all items that have match with other array


I'm creating a query but i came a section when i don't have idea that how do it. I have one array that have for example two items

//filter array
const filterArray=r.expr(['parking', 'pool'])

and also i have one table with follows records:

[
    {
        "properties": {
            "facilities": [
                "parking"
            ],
            "name": "Suba"
        }
    },
    {
        "properties": {
            "facilities": [
                "parking",
                "pool",
                "pet friendly"
            ],
            "name": "Kennedy",
        }
    },
    {
        "properties": {
            "facilities": [
                "parking",
                "pool"
            ],
            "name": "Soacha"
        }
    },
    {
        "properties": {
            "facilities": [
                "parking",
                "pet friendly",
                "GYM"
            ],
            "name": "Sta Librada"
        }
    },
]

I need filter the records with the array but i need that record has all items of array filter. If the record has more item of array filter not is problem, i need if contains all items of array filter get that record. On this case I need all records that have the facilities "pool" and "parking"

Current query

Current query but it also return records with one or two items of the filter array

r.db('aucroom').table('hosts')
.filter(host=>
    host('properties')('facilities').contains(val=>{
        return filterArray.contains(val2=>val2.eq(val))

    })
)
.orderBy('properties')
.pluck(['properties'])

results that I desire wait

Like the image example:

enter image description here


Solution

  • If you want a strict match of two arrays (same number of elements, same order), then use .eq()

    array1.eq(array2)
    

    If you want the first array to contain all elements of the second array, then use .setIntersection(), just note array2 should contain distinct elements (a set):

    array1.setIntersection(array2).eq(array2)