Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
JavaScript Return an array that contains all the strings appearing in all the subarrays
We have an array of arrays like this ?
const arr = [ ['foo', 'bar', 'hey', 'oi'], ['foo', 'bar', 'hey'], ['foo', 'bar', 'anything'], ['bar', 'anything'] ]
We are required to write a JavaScript function that takes in such array and returns an array that contains all the strings which appears in all the subarrays.
Let's write the code for this function
Example
const arr = [
['foo', 'bar', 'hey', 'oi'],
['foo', 'bar', 'hey'],
['foo', 'bar', 'anything'],
['bar', 'anything']
];
const commonArray = arr => {
return arr.reduce((acc, val, index) => {
return acc.filter(el => val.indexOf(el) !== -1);
});
};
console.log(commonArray(arr));
Output
The output in the console will be ?
['bar']
How It Works
The function uses the reduce() method to iterate through each subarray. Starting with the first subarray as the accumulator, it filters elements that exist in the current subarray using indexOf(). Only elements present in all subarrays remain after the reduction.
Alternative Approach Using Set
const arr = [
['foo', 'bar', 'hey', 'oi'],
['foo', 'bar', 'hey'],
['foo', 'bar', 'anything'],
['bar', 'anything']
];
const findCommonStrings = arr => {
if (arr.length === 0) return [];
return arr[0].filter(element =>
arr.every(subarray => subarray.includes(element))
);
};
console.log(findCommonStrings(arr));
['bar']
Comparison
| Method | Readability | Performance | Notes |
|---|---|---|---|
| reduce() + filter() | Medium | Good | Functional programming approach |
| filter() + every() | High | Good | More intuitive logic |
Conclusion
Both approaches effectively find common elements across all subarrays. The filter() + every() method is more readable, while reduce() offers a functional programming style for finding intersections.
