4
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.

3 Answers 3

2

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

Thats my problem. How to parse and remove that outer array?
I need to fetch the arrayValues[0], arrayValues[1] dynamically.
0

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]);

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.