'realm react-native: how to query correctly an array of strings

can someone show me how to query an array of strings with realm in react-native?

assume i have an array like the following:

const preferences = ["automatic","suv","blue",eco]

What I want is to get realm results where ALL strings in the attribute "specifications" of Cars is in "preferences".

E.g.: If an instance of Cars.specifications contains ["automatic","suv"] a result should be returned.

But if an instance of Cars.specifications contained ["automatic,"suv","green"] this instance shouldn't be returned.

The length of preferences can vary.

Thank you very much.

Update:

What i tried is the following:

const query = realm.objects("Cars").filtered('specifications = preferences[0] OR specifications = preferences[1]')

As you see it is an OR operator which is surely wrong and it is hardcoded. Looping with realm really confuses me.



Solution 1:[1]

This code will work!

const collection = realm.objects('Cars');
const preferences = ["automatic","suv","blue","eco"];
let queryString = 'ANY ';
for (let i = 0; i < preferences.length; i++) {
         if (i === 0) {
              queryString += `specifications CONTAINS '${preferences[i]}'`;
            }
          if (i !== 0 && i + 1 <= preferences.length) {
                    queryString += ` OR specifications CONTAINS '${preferences[i]}'`;
          }
}
const matchedResult = collection.filtered(queryString);

Solution 2:[2]

example of function to test if a word is inside an array of word

function inArray(word, array) {
  var lgth = array.length;
  word = word.toLowerCase();
  for (var i = 0; i < lgth; i++) { 
    array[i] = (array[i]).toLowerCase();
    if (array[i] == word) return true;
  }

  return false;
}

const preferences = ["automatic","suv","blue","eco"];

const specifications = ["automatic","suv"] ;
const specifications2 = ["automatic","suv", "boat"] ;

function test(spec,pref){ 
  for (var i in spec){
    if(!inArray(spec[i],pref)){
      return false ;
    }    
  }
  return true;   
}

console.log(test(specifications,preferences));
console.log(test(specifications2,preferences));

https://jsfiddle.net/y1dz2gvu/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 AlainIb