-2

I can't seem to find an answer to this question because I don't really know what this is called, if there's a solution already point me there.

I'm trying to use this from underscore.js

_.intersection(*arrays)

I understand I can use the function like so:

var intersection = _.intersection(['a','b'], ['a','c'])

and get ['a'] back.

I have a variable amount of arrays however, so I want to do something like this:

var intersection = _.intersection(array for array in my_arrays)

I understand I could do this:

var intersection = my_arrays[0];
my_arrays.forEach(arr => intersection = _.intersection(intersection, arr) )

But that doesn't seem clean. How can this be done? Thanks.

MarkMan
  • 159
  • 1
  • 7
  • do you habe an example of the given data and the wanted result? – Nina Scholz Nov 25 '20 at 18:27
  • Does this answer your question? [Passing an array as a function parameter in JavaScript](https://stackoverflow.com/questions/2856059/passing-an-array-as-a-function-parameter-in-javascript) – jonrsharpe Nov 25 '20 at 18:28
  • No matter how a JavaScript function is declared, you can pass as many arguments as you want when you call the function. Whether it works or not depends on the particular function involved. – Pointy Nov 25 '20 at 18:28
  • `_.intersection(...arrays)`? – user3840170 Nov 25 '20 at 18:28
  • That's just the documentation convention for the Underscore library. – Pointy Nov 25 '20 at 18:29

1 Answers1

2

Most modern browsers support ES6 so you can use the spread operator to do this:

const my_arrays = [[1, 2], [1, 3, 4], [1, 5, 6, 7]];
dummy_intersection(...my_arrays);

function dummy_intersection(...arrays) {
  console.log(arrays[0]);
}

On a side note, it's generally considered a better idea to use lodash than underscore.

technophyle
  • 7,972
  • 6
  • 29
  • 50