- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Finding Common Item Between Arbitrary Number of Arrays in JavaScript
Suppose, we have an object of arrays of Numbers like this −
const obj = { a: [ 15, 23, 36, 49, 104, 211 ], b: [ 9, 12, 23 ], c: [ 11, 17, 18, 23, 38 ], d: [ 13, 21, 23, 27, 40, 85] };
The number of elements in the object are not fixed and it can have any arbitrary number of elements.
We are required to write a JavaScript function that takes in one such object and returns an array of elements that are common to each member array.
Therefore, for the above object, the output should be −
const output = [23];
Example
The code for this will be −
const obj = { a: [ 15, 23, 36, 49, 104, 211 ], b: [ 9, 12, 23 ], c: [ 11, 17, 18, 23, 38 ], d: [ 13, 21, 23, 27, 40, 85] }; const commonBetweenTwo = (arr1, arr2) => { const res = []; for(let i = 0; i < arr1.length; i++){ if(arr2.includes(arr1[i])){ res.push(arr1[i]); }; }; return res; }; const commonBetweenMany = (obj = {}) => { const keys = Object.keys(obj); let res = obj[keys[0]]; for(let i = 1; i < keys.length - 1; i++){ res = commonBetweenTwo(res, obj[keys[i]]); if(!res.length){ return []; }; }; return res; }; console.log(commonBetweenMany(obj));
Output
And the output in the console will be −
[23]
- Related Articles
- Finding the missing number between two arrays of literals in JavaScript
- Finding the common streak in two arrays in JavaScript
- Finding the sum of all common elements within arrays using JavaScript
- Finding deviations in two Number arrays in JavaScript
- Finding maximum number from two arrays in JavaScript
- Finding the difference between two arrays - JavaScript
- Finding a number of pairs from arrays with smallest sums in JavaScript
- Finding the inclination of arrays in JavaScript
- Finding intersection of multiple arrays - JavaScript
- Finding intersection of arrays of intervals in JavaScript
- Finding the longest common consecutive substring between two strings in JavaScript
- Finding Number of Days Between Two Dates JavaScript
- Finding maximum length of common subarray in JavaScript
- Finding reversed index of elements in arrays - JavaScript
- Finding the continuity of two arrays in JavaScript

Advertisements