简体   繁体   中英

How to get intersection of the arrays in a nested array

I have an array like the following which is computed from another function I don't want to modify.

var d = [[1, 2, 3], [2, 3], [1, 3]];

I want to use _.intersection with all the arrays within the above array like this:

var c = _.intersection(d);
// should return [3]

but _.intersection takes multiple array parameters as input, not an array of arrays.

I have tried to flatten an array using something similar to Merge/flatten an array of arrays in JavaScript? but it convert the whole array into a single array.

var merged = [].concat.apply([], d);    
[1, 2, 3, 2, 3, 1, 3]; // I don't want this 

Let me explain this in detail. I have a nested array d (which contains arrays and length is dynamic). Now I want to find the intersection of all arrays that are within array d .

How can I call _.intersection([1, 2, 3], [2, 3], [1, 3], ...) but dynamically with d ?

In ES5 you can use Function#apply to spread the array into parameters:

 var d = [[1, 2, 3], [2, 3], [1, 3]]; var result = _.intersection.apply(_, d); console.log(result); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script> 

You can use lodash's _.spread that will convert a function to consume an array of parameters:

 var d = [[1, 2, 3], [2, 3], [1, 3]]; var result = _.spread(_.intersection)(d); console.log(result); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script> 

In ES6 you can use the spread syntax to do the same thing:

 const d = [[1, 2, 3], [2, 3], [1, 3]]; const result = _.intersection(...d); console.log(result); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script> 

Your desired result is not a data structure js would support. However, you can destructure the arrays into variables:

 let [a,b,c] = [[1, 2, 3], [2, 3], [1, 3]]; console.log(a,b,c); 

The only valid representation of what you want to get is a string. You can get the exact result you've asked for like that :-) :

 let d = [ [1, 2, 3], [2, 3], [1, 3] ]; function createString(arr) { let s = arr.map(el => `[${el}]`).join(", "); return `result ${s};`; } console.log(createString(d)); 

The only way to do that is to put each of those internal arrays into a separate variable. With ES6, it's as easy as:

let d = [[1, 2, 3], [2, 3], [1, 3]];
let [arr1, arr2, arr3] = d;
// -> arr1: [1, 2, 3], arr2: [2, 3], arr3: [1, 3]

Otherwise, you can do it using the standard ES5 syntax of course.

The only way you'll be able to work with all of those internal arrays with the same variable is to use the parent array you already have, d .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM