How to check array in array with "Underscore"?


#1

I would like to check array in array with underscore

var a = [1, 2, 3];
var b= [1, 2, 3, 4, 5]

check a in b // true

Please help me.


#2

Would Lodash Difference work for you?
https://lodash.com/docs#difference

If array B is the one you compare everything at, you could check the difference between A and B and deduce from that if array A is in (or partially in) B.

Lodash is an extention of underscore, package you can use is:
meteor add stevezhu:lodash

Don’t forget to initiate lodash in your Lib folder like:

@_ = lodash

If you don’t do that, the _ namespace will be still assigned to Underscore and not Lodash

Alternative solution would be to use _.map and loop through B and check during each iteration if the value of the current B array element is part of array A (using IndexOf or something)


#3

Hi, may be :

(_.size(_.difference(a,b)) == 0) ? true : false;

#4
var aIsInB = !_.difference(a, b).length;

#5

I use sugar.js for that http://sugarjs.com/api/Array/intersect

You’d simply do an intersect of a and b and compare the result to a.


#6

Look great for Sugar JS.
I missing before…


#7

SugarJS:

[1,3,5].intersect([5,7,9]) => [5]

UnderscoreJs:

_.intersection([1,3,5],[5,7,9]) => [5]