Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to push array or objects into one array using underscore?

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}})
like image 630
user1595858 Avatar asked Apr 26 '26 13:04

user1595858


2 Answers

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);
like image 181
Sushanth -- Avatar answered Apr 29 '26 02:04

Sushanth --


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}})
like image 36
SteamDev Avatar answered Apr 29 '26 03:04

SteamDev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!