Reputation: 193
var arrayValues = [[2,3,5],[3,5]]
var commonArrayValues = _.intersection(arrayValues);
Currently it is working as,
_.intersection([[2,3,5],[3,5]])
Result: [2,3,5]
But it should work as, (i.e outer array should be removed)
_.intersection([2,3,5],[3,5])
Expected Result: [3,5]
Anyone kindly give me a proper solutions. Thank you in advance.
Upvotes: 4
Views: 339
Reputation: 27986
You can use apply with intersection to get what you want:
var result = _.intersection.apply(null, arrayValues);
var arrayValues = [[2,3,5],[3,5], [2,3,5,6]]
var result = _.intersection.apply(null, arrayValues);
document.getElementById('results').textContent = JSON.stringify(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore.js"></script>
<pre id="results"></pre>
Upvotes: 2
Reputation: 783
The only way I can think of is using eval:
var arrayValues = [[2,3,5],[3,5]]
var evalString = '_.intersection(';
arrayValues.forEach(function (element, index){
evalString += 'arrayValues['+index+'],';
});
evalString =evalString.slice(0, -1);
evalString += ');'
eval(evalString);
evalString would end being something like _.intersection(arrayValues[0],arrayValues[1],...,arrayValues[n]);
Upvotes: 0
Reputation: 7133
intersection *_.intersection(arrays)
Computes the list of values that are the intersection of all the arrays. Each value in the result is present in each of the arrays._.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]); => [1, 2]
var arrayValues = [[2,3,5],[3,5]]
Here arrayValues is an array having 2 arrays. Where as _.intersection expects arrays as parameter and not an array having arrays.
_.intersection([2,3,5],[3,5])
Or
_.intersection(arrayValues[0],arrayValues[1])
will output as what you need.
Upvotes: 0