Commons including duplicates in array elements in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in an array of strings, arr, as the first and the only argument.

Our function is supposed to return an array of all characters that show up in all strings within the array arr (including duplicates).

For example, if a character occurs 2 times in all strings but not 3 times, we need to include that character 2 times in the final answer.

For example, if the input to the function is −

const arr = ['door', 'floor', 'crook'];

Then the output should be −

const output = ['r', 'o', 'o'];

Example

The code for this will be −

 Live Demo

const arr = ['door', 'floor', 'crook'];
const findCommon = (arr = []) => {
   let prev = null;
   arr.forEach((str) => {
      const next = {};
      for(const val of str){
         if(!prev){
            next[val] = (next[val] || 0) + 1;
         }else if(prev[val]){
            prev[val] -= 1;
            next[val] = (next[val] || 0) + 1;
         };
      };
      prev = next;
   });
   const res = Object.keys(prev).reduce((acc, val) => {
      for(let i = 0; i < prev[val]; i++){
         acc.push(val);
      }
      return acc
   }, []);
   return res;
};
console.log(findCommon(arr));

Output

And the output in the console will be −

[ 'r', 'o', 'o' ]
raja
Published on 09-Apr-2021 08:27:37
Advertisements