![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 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']
Advertisements