Reputation: 3890
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}})
Upvotes: 2
Views: 11724
Reputation: 4404
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}})
Upvotes: 2
Reputation: 3435
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
Upvotes: 1
Reputation: 55750
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);
Upvotes: 6