JavaScript function that takes a multidimensional and a single array, and finds matches of the single array in the multi-d array

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of arrays of Numbers as the first argument and an array of Numbers as the second argument. The function should pick a subarray from each array of the first array, (subarray that contains item common to both the second array and the corresponding array of first array.)

For example −

If the inputs are −

Example

const arr1 = [
[1,2,5,6],
[5,13,7,8],
[9,11,13,15],
[13,14,15,16],
[1,9,11,12]
];
const arr2 = [9,11,13,15,1,2,5,6];

Output

And the output in the console will be −

const output = [
[1, 2, 5, 6],
[5, 13],
[9, 11, 13, 15],
[13, 15],
[1, 9, 11]
]

Common elements between first subarray of first array and second array forms the first subarray of output array.

Common elements between second subarray of first array and second array forms the second subarray of output array. And so on.

Example

const arr1 = [
[1,2,5,6],
[5,13,7,8],
[9,11,13,15],
[13,14,15,16],
[1,9,11,12]
];
const arr2 = [9,11,13,15,1,2,5,6];
const findIntersection = (arr1 = [], arr2 = []) => {
   const regex = new RegExp('\\b(' + arr1.join('|') + ')\\b', 'g');
   const res = [];    
   arr2.forEach(arr => {
      let matches = arr.join(' ').match(regex);
      if (matches.length) {          
         res.push(matches.map(Number));
      };
   });
   return res;
}
console.log(findIntersection(arr2, arr1));

Output

And the output in the console will be −

[
   [ 1, 2, 5, 6 ],
   [ 5, 13 ],
   [ 9, 11, 13, 15 ],
   [ 13, 15 ],
   [ 1, 9, 11 ]
]
raja
Published on 21-Nov-2020 05:47:14
Advertisements