Home > Software design >  How to get array with intersected elements?
How to get array with intersected elements?

Time:02-08

I have an array, that contains another arrays with string id's. I need to get an array with string ids, that are exists in all arrays of parent.

Here is example:

const parentArray = [ ['test1', 'test2', 'test3'], ['test2', 'test4', 'test5'], ['test3', 'test2', 'test6']];

//some magic. Maybe use lodash instersection func

console.log(result) => ['test2']

Important note! I don't know, how much arrays of elements in parent array, thats the problem that i cant understand how to use lodash intersection function:(

CodePudding user response:

const parentArray = [ ['test1', 'test2', 'test3'], ['test2', 'test4', 'test5'], ['test3', 'test2', 'test6']];

let common = parentArray.reduce((p,c) => p.filter(e => c.includes(e)));

// ['test2']

CodePudding user response:

The below may be one possible way to achieve the desired result.

Code Sample

const commonElements = (arr1, arr2) => (
    arr1.length === 0
   ? arr2
   : [...(new Set([...arr1, ...arr2]))]
    .filter(
      x => arr1.includes(x) && arr2.includes(x)
    )
);

const intersectAllElements = (arr = parentArray) => (
    arr.reduce(
    (fin, itm) => (commonElements(fin, itm)),
    []
  )
);

Explanation

  • Set a helper-method named commonElements that will share either common elements between 2 arrays, or if the first array is empty then the second array
  • Iterate over the parentArray using .reduce
  • Initialize the aggregator fin as an empty array
  • For each item (which will be an array) in parentArray, track the common elements between the aggregator and given item

Code Snippet

const parentArray = [ ['test1', 'test2', 'test3'], ['test2', 'test4', 'test5'], ['test3', 'test2', 'test6']];

const commonElements = (arr1, arr2) => (
    arr1.length === 0
   ? arr2
   : [...(new Set([...arr1, ...arr2]))]
    .filter(
      x => arr1.includes(x) && arr2.includes(x)
    )
);

const intersectAllElements = (arr = parentArray) => (
    arr.reduce(
    (fin, itm) => (commonElements(fin, itm)),
    []
  )
);

console.log(intersectAllElements());

CodePudding user response:

Lodash solution:

const parentArray=[["test1","test2","test3"],["test2","test4","test5"],["test3","test2","test6"]];

const result = parentArray.reduce((acc, arr) => _.intersection(acc, arr));

console.log(result);
.as-console-wrapper{min-height: 100%!important; top: 0}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

  •  Tags:  
  • Related