2

I'm basically using $all operator in mongo and the input i get might be array or single element as following. So how do use underscore to put all the elements in one array and then

userId = 'a';
userIds = ['a', 'b', 'c'];
otherId = ['a'] or 'a';
searchArray = [userId, userIds, otherId]
db.collections.find({userIds: {$all: searchArray}})

3 Answers 3

6

You can use union as long as they are arrays.

_.union(arrays) 

var userId = ['a'],
    userIds = ['a', 'b', 'c'];
    otherId = ['a'],

searchArray = _.union(userId, userIds, otherId);
Sign up to request clarification or add additional context in comments.

Comments

2

If all variables aren't promised to be arrays, you probably want the flatten method.

userId = 'a'; // strings
userIds = ['a', 'b', ['c']]; // multidimensional array
otherId = ['a']; // single dimensional array
searchArray = _.flatten([userId, userIds, otherId]);
db.collections.find({userIds: {$all: searchArray}})

Comments

1

No need for underscore, you can use concat:

var userId = ['a'],
    userIds = ['a', 'b', 'c'],
    otherId = ['a'];

var arr = userId.concat(userIds, otherId)

This will work even if one of those is not an array but just a number or string. Working example here:

http://codepen.io/anon/pen/qbNQLw

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.