rethinkdbrethinkdb-javascript

RethinkDB filter array, return only matched values


I have a table like this

{
  dummy: [
     "new val",
     "new val 2",
     "new val 3",
     "other",
  ]   
}

want to get only matched values to "new", I am using query like this:

r.db('db').table('table')('dummy').filter(function (val) {
 return val.match("^new")
})

but its giving error

e: Expected type STRING but found ARRAY in

what is wrong with query, if I remove .match("^new"), it returns all values

Thanks


Solution

  • The reason of why you're getting Expected type STRING but found ARRAY in is that the value of the dummy field is an array itself, and you cannot apply match to arrays. Despite the filter you tried may look confusing, you have to rethink your query a bit: just remap the array to a new ^new-keyed array, and then just filter its values out in an inner expression. For example:

    r.db('db')
        .table('table')
        .getField('dummy')
        .map((array) => array.filter((element) => element.match("^new")))
    

    Output:

    [
        "new val" ,
        "new val 2" ,
        "new val 3"
    ]