

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
JavaScript function that takes a multidimensional and a single array, and finds matches of the single array in the multi-d array
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 ] ]
- Related Questions & Answers
- Single dimensional array vs multidimensional array in JavaScript.
- Creating a JavaScript Object from Single Array and Defining the Key Value?
- How do I write a function that takes an array of values and returns an object JavaScript?
- What are the differences between a multi-dimensional array and jagged array?
- Write an algorithm that takes an array and moves all of the zeros to the end JavaScript
- How to Map multi-dimensional arrays to a single array in java?
- How to sum elements at the same index in array of arrays into a single array? JavaScript
- Differentiate between a single processor and a multi-processor.
- Function that returns the minimum and maximum value of an array in JavaScript
- Maps in JavaScript takes keys and values array and maps the values to the corresponding keys
- Single dimensional array in Java
- Grouping and sorting 2-D array in JavaScript
- Single-threaded and Multi-threaded Processes
- Single Element in a Sorted Array in C++
- Finding transpose of a 2-D array JavaScript
Advertisements