How to use .contains with array? - rethinkdb

I have an array in a document that contains a list of user ids.
I'd like to find all documents that have this list of user ids.
I know I can do something like:
r.db('unicorn')
.table('rooms').filter(function(doc){
return doc('people').contains(
"id-one","id-two"
)
})
I know this will work great, but I have to hardcode things. How do I pass the contains function an array of values to match against?

After a little digging, The simplest solution was to use args. Was a bit non-obvious from the examples. This way I can pass in dynamic values and run commands with them.
r.db('unicorn')
.table('rooms').filter(function(doc){
return doc('people').contains(
r.args(["id-one","id-two"])
)
})

You can use setIntersection and pass array:
r.db('unicorn')
.table('rooms').filter(function(doc){
return doc('people').default([]).setIntersection(
["id-one","id-two"]
).count().eq(2)
})
So, if you have array:
var myArr = ["id-one","id-two"];
You can write query like this:
r.db('unicorn')
.table('rooms').filter(function(doc){
return doc('people').default([]).setIntersection(myArr).count().eq(myArr.length)
})

Related

Return True if Array Contains a Specific String - JSONata

Is there a way in JSONata to have a function return TRUE if it finds a specific string within a provided array? For example I have an array of colors:
const myArray = [red,blue,green,pink]
I am trying to figure out an expression that would search that array for "blue" and return true if it finds the value.
On the JSONata documentation, I found a function called $boolean(arg)that I think I would need to use but I'm not sure how to implement it. The documentation shows an argument type option as "array: contains a member that casts to true", but I can't really tell how to implement it.
Would it be as simple as $boolean(myArray, "blue")?
The in operator is what you need. See https://docs.jsonata.org/comparison-operators#in-inclusion
In your case, the expression "blue" in myArray will return true. See https://try.jsonata.org/r0q7GnSOh
edit: Thought this was python, but maybe you could use something similar for JSONata
you can make a for loop with an if condition to check your condition
listOfStrings = ['red','green','blue']
for strings in listOfStrings:
if listOfStrings[strings] == 'blue':
return True

Lodash sortedby object list is stuck in _wrapper_

I am experimenting with lodash sorting. I got the lodash to sort the object list although the sorted results are stuck in wrapper. If I use .value(), then I get unsorted keys output.
var testData = {c:1,b:2,a:3}
var sortedKeys = _(testData).keys().sortBy(key => {return testData.key});
console.log(sortedKeys);
will produce:
LodashWrapper {__wrapped__: {…}, __actions__: Array(2), __chain__: false, __index__: 0, __values__: undefined}
__actions__:(2) [{…}, {…}]
__chain__:false
__index__:0
__values__:undefined
__wrapped__:
a:3
b:2
c:1
__proto__:Object
__proto__:lodash
What is it that I am missing in order to get sorted object list out of lodash wrapper.
When you do testData.key, I'm pretty confident that you actually mean to be doing testData[key].
That alone allows the method to work properly i.e. return an array of Object keys sorted by values. Note that you still have to call .value() if you'd like to unwrap the lodash object.
If there's something else you're expecting, please clarify.
const testData = {c:1,b:2,a:0}
const sortedKeys = _(testData).keys().sortBy(key => {return testData[key]})
/* can do without the return like the below as well */
// const sortedKeys = _(testData).keys().sortBy(key => testData[key])
console.log(sortedKeys.value())
// produces ['a','c','b']
If you want the key and value pair, try the below.
_(obj).toPairs().sortBy(0).value()
There are few things that are happening here which I think are important to note:
First you are starting your sorting statement with the short notation for the lodash _.chain method which allows the results of one operation to flow into the next one. This is similar to how _.flow works in lodash/fp.
Chaining requires the last operation in the chain to end with values() in order to get your actual result from the lodash wrapper. So if you did:
_(testData).keys().sortBy(key => {return testData.key}).values(); // OR
_.chian(testData).keys().sortBy(key => {return testData.key}).values();
You would get some results.
Second issue is that in your flow you get the keys of the objects but then you are not actually sorting by them. To do this you need something like this:
var testData = {c:1, b:2, a:3}
console.log(_.chain(testData).keys().sortBy().value());
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
The difference here is in the sort function where you already have the keys as `[ 'c', 'b', 'a' ] so you just need to sort them. They are not objects anymore but simply strings.
Hope this helps.

How to retrieve an array of values from an array of ActiveRecord objects with 'each' method?

I'm trying to perform this non-basic query with Rails :
proj_repartitions = ProjRepartition.includes(:proj_contributions).find( proj_project.proj_charges.each{|pc| pc.proj_repartition_id} )
The point is I need to pass an array of 'ids' to the find method.
I want to extract those 'ids' from an array of ActiveRecord objects where each of these is equipped with an 'id' attribute.
When I try on the Rails console:
proj_project.proj_charges.each{|pc| pc.proj_repartition_id}
I got exactly the same array as proj_project.proj_charges
What am I doing wrong?
=== UPDATE ===
According to the answers, my definitive working code is:
proj_project.proj_charges.collect{|pc| pc.proj_repartition_id}
Instead of using each try map or collect - they should return an array.
Each only executes the do block code for each item but doesn't "save" the return value.
Collect and Map executes the do block code for each item and the return value in an array.
hope that makes sense
proj_project.proj_charges.map(&:proj_repartition_id)
Short way of writing
proj_project.proj_charges.map{|pc| pc.proj_repartition_id}

What is the proper way to define an array of values for the IN operator in Active Record

I need to search my data for rows who's value is contained in an array of strings. What is the proper way to do this in Active Record?
For example, say I have this array:
["fluffy", "spot"]
I want the SQL to look something like this:
select * FROM Pets WHERE name IN ('fluffy', 'spot')
The following works:
list = ["fluffy", "spot"].map { |x| "'#{x}'" }.join(', ')
Pet.where("name in (#{list})")
Obviously this is a bad idea. What is the correct method to do this? Is there a way to use parameters in this way, or does Active Record have a special method for this?
list = ["fluffy", "spot"]
Pet.where(:name => list)

Prototype: how to dynamically construct selector?

I am having a little bit of difficulty passing a variable into a selector in prototype. I would like to be able to pass a variable into the select string, so that one function can work for many of the same kind.
At the moment, this is what I would basically like to do:
function myFunct(var)
{
$(var + 'add_form').hide() //so inde the brackets would be ('#product1 #add_form') for example.
}
Be able to pass 'var' into the function that would pass it to the selector, so that I can hide a pattern that is the same for many on the page.
Any ideas for a path to follow would be greatly appreciated.
You're on the right track! Couple things:
var is a JavaScript keyword (source), don't use it to name a variable
if you're querying an element by id (such as #add_form) you don't need to add any container element as you're doing
If you're querying an element by class, you need to use the $$ function, not the $ function
You need to iterate over the wrapped set to call your method
whitespace is significant in css selectors, so make sure to include those in your selector construction to tell Prototype to search within your parent container:
function myFunct(parent) {
$$(parent + ' .add_form').invoke('hide')
}
myFunct('#someparent'); // hides .add_form inside #someparent
That should work... just rename var to something else.
function myFunct(yourVar)
{
$$('#' + yourVar + ' .add_form').each(function(s){ s.hide(); }); // yourVar being the id of the container element
}
I've put a '.' in front of add_form because you can't use multiple elements with same ID, make it a class.

Resources