Finding Common Item Between Arbitrary Number of Arrays in JavaScript


The problem statement tells you to find a solution for an arbitrary number of arrays such that the user needs to find a common element present in every arbitrary array. The arbitrary array is referred to here as an object of arrays . One should not confuse finding common elements between two arrays , it is not what the problem statement is asking for. It defines and explores the variety of algorithms that can help us find the least common factors present in mutual by the given source data in JavaScript.

What are Arbitrary Number of Arrays in JavaScript

Arbitrary number refers to an undetermined large number of values that do not follow any specific patterns , you just provide them values very randomly . Similarly arbitrary number of arrays refers to more than two sets of arrays that are given random elements where such a number of different arrays are packed together in an object called an object of arrays. The problem statement says to find intersection elements present in such random , different and more than two countable sets of arrays.

The different sets of arrays can be packed together in an array of arrays or objects of arrays , as such ought to condition is not mentioned in the problem statement .

The algorithm here discusses the problem statement to be solved for arbitrary numbers of arrays present in an array itself .

Step 1 : Declare a function with the name findCommonElements that takes in array input as the source .

Step 2 : Declare and initialize resultant array with empty array as well.

Step 3 : Traverse the first array of all the arbitrary arrays using outer for loop where i indexing will track the first array and its elements going from backward direction from arr.length-1 because in such cases where there is huge arrays or multiple arrays with in an array , it is not efficient to compute length property every time for each iteration in a loop , it is not enough trivial .

Step 4 : The nested second loop will traverse the leftover sets of array or left over arbitrary arrays present in the big array with j indexing .

Step 5 : indexOf method is used to find the value of elements present in the first array into the left over arbitrary sets .

Step 6 : If the particular value of the first array is not found in left over arrays , we just use the break statement to skip to the next iteration and try to find the element common in other arbitrary arrays .

Step 7 : Once all the loops are over , we use j indexing to say if its value reached to the first array itself , which is the main source of comparing , just push whatever value we get from arr[0][i] during comparison into the resultant array because a array cannot compare with itself .

Main Code - using loop

Example

function findCommonElements(arr) {
  let commonArray = [];
  for (let i = arr[0].length - 1; i >= 0; i--) {
   let isCommon = true;
   for (let j = arr.length - 1; j > 0; j--) {
    if (arr[j].indexOf(arr[0][i]) === -1) {
     isCommon = false;
     break;
    }
   }
   if (isCommon) {
    commonArray.push(arr[0][i]);
   }
  }
  return commonArray;
}

const arrayOfArrays = [
  [1, 4, 6, 78, 8, 9, 124, 44],
  [44, 6, 9],
  [124, 44, 16, 9]
];

console.log(findCommonElements(arrayOfArrays));

Output

[ 44, 9 ]

Time and Space Complexity

In the above algorithm we have used a nested loop that goes till the length of the array hence resulting in O(n^2) time complexity at its worst . The space complexity is O(1)

The above algorithm can be optimized using maps and sets in javascript by following

Algorithm - using Map and Set

The algorithm is more efficient now in respect to time complexity but sacrificing space complexity for sure ,

Step 1 : Declare a function with name commonElementFindthat takes in mainArray as an input source.

Step 2 : Declare and initialize a map with an empty value .

Step 3 : We will traverse every sub array of arrays to create nd convert each subarray into the Set in javascript to remove duplicates and make the algorithm more efficient and quicker in finding common element present in the arbitrary number of arrays

Step 4 : Once each subarray is converted into each unique set we will now set their values in map we created by counting their number of occurrences in a whole common and single map

Step 5 : If the value of set is already is present in map , increment it by 1 else initialize and assign it with value 1

Step 6 : Once all loops and traversing of each Set element is done , we will map the keys of the Object to check if the length of any key of the map is equal to the length of array that will surely indicate the common element behavior

Step 7 : Once we find the key that is equal to array length that means that particular element has occurred in all sub arrays of arrays and hence we find the value or common element present in an arbitrary number of arrays in javascript.

Main Code - using Map and Set

Example

function commonElementFind(mainArray)
{   

   const newMap = {};

   for(let subArray of mainArray)
   {  

     const newSet = new Set(subArray);

         newSet.forEach(val => {

       if(newMap[val])
       { 
         newMap[val] = newMap[val] + 1;
       }
       else 
       {
         newMap[val] = 1;
       }
   })

   }
Object.keys(newMap).map((key)=> {

     if(newMap[key] === arr.length) {

       console.log(key);

     }
   });
}

const arr = [
   [15, 23, 36, 49, 104, 211],
   [9, 12, 23],
   [11, 17, 18, 23, 38],
   [13, 21, 23, 27, 40, 85]
  ];
  
  commonElementFind(arr);

Output

23

Time and Space Complexity

As we have optimized the algorithm using Map and Set , powerful concepts of javascript it graphs down the time complexity of algorithm from O(n^2) to O(n) but as the map and set is used for extra memory allocation , we have sacrificed the space complexity to linear time as well i.e. O(n) .

Conclusion

This is how we can solve the above problem statement thinking logically and efficiently in the context of coding taking code from nested loops to Map and Set functionality which gives us immense power to traverse and perform operations using it in linear time of time and space complexity .

Updated on: 22-Aug-2023

144 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements