skip to Main Content

I’m searching for a way for extracting common values in at least two arrays in the list of arrays in JS.

e.g. [["google", "amazon", "reddit"], ["telegram", "reddit", "discord"], ["firefox", "telegram", "chrome"]] to ["reddit", "telegram]

The point is 1. the arrays can be any length 2. common at least two (or any specified number) of arrays but not all of the arrays.

I looked a countless numbers of SO posts and also looked the lodash functions, they are all talking either "of two arrays" or "of all arrays from multiple arrays", none of them were takling "of two/arbitrary arrays from multiple arrays". So I’m here to ask.

Thanks.

2

Answers


  1. You can create a function by passing the array and the occurrences. You can maintain an occurrences object to store the item occurrences in the arrays. Then iterates over each array, incrementing the occurrence count in the occurrences object.

    If occurrences match then store the item in the result array.

    Finally, return the result.

    Demo:

    function filterCommon(arrays, occr) {
      var occurrences = {};
      var res = [];
    
      //count occurrences of each value across arrays
      arrays.forEach(function(array) {
        array.forEach(function(value) {
          occurrences[value] = (occurrences[value] || 0) + 1;
          //if occurences match then store the item
          if(occurrences[value] == occr) res.push(value)
        });
      });
    
      return res;
    }
    
    var arrays = [["google", "amazon", "reddit"], ["telegram", "reddit", "discord"], ["firefox", "telegram", "chrome"]];
    var occr = 2;
    
    var commonItem = filterCommon(arrays, occr);
    console.log(commonItem);
    Login or Signup to reply.
  2. If you don’t need flexibility with the amount of arrays that have a common value, you can do this:

    Demo:

    const getCommonWords = (wordLists) => {
      const commonWords = [];
      const words = new Set();
    
      wordLists.forEach((wordList) => {
        wordList.forEach((word) => {
          if (words.has(word)) {
            commonWords.push(word);
          } else {
            words.add(word);
          }
        });
      });
    
      return commonWords;
    };
    
    const list = [["google", "amazon", "reddit"], ["telegram", "reddit", "discord"], ["firefox", "telegram", "chrome"]];
    
    console.log(getCommonWords(list));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search