Finding Common Item Between Arbitrary Number of Arrays in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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]
raja
Updated on 21-Nov-2020 10:21:27

Advertisements