Search code examples
javascriptcomparedynamic-arrays

Looking for suggestions on how to compare multiple arrays in javascript


I need to iterate through n number of arrays with n number of items ,find the matches in each array, create a new array with those items, if there are no item matches for any of the arrays, that would be undefined, for each array that doesn't match, in the new array.

I can do this with 2 arrays but looking for suggestions on how to do it for any number. I'm not necessary looking for you to code it, just some suggestions on how to tackle the problem

const one = [[1,2,3,4,5],[3,4,5,6,7,8], [3,4,5,9,10]]

The results should be this

[[1,undefined,undefined], [2,undefined,undefined], [3,3,3],[4,4,4],[5,5,5], [undefined,6,undefined], [undefined, 7,undefined], [undefined, 8, undefined],[undefined,undefined,9], [undefined,undefined,10]]

Solution

  • You can make liberal use of Sets. First, convert each inner list to a set so that you can check if a number is in it fast. Next, you can create a set of all numbers in all lists and, for each number, get your desired list based on whether or not it is contained in each "inner-list set" created earlier:

    const one = [
      [1, 2, 3, 4, 5],
      [3, 4, 5, 6, 7, 8],
      [3, 4, 5, 9, 10]
    ];
    
    const sets = one.map(arr => new Set(arr));
    const allNumbers = new Set(one.reduce((acc, curr) => {
      acc.push(...curr);
      return acc;
    }, []));
    
    const result = [...allNumbers].map(n => sets.map(s => s.has(n) ? n : undefined));
    console.log(result);

    The trade-off is that the list of sets takes up extra memory (as much as the original 2-d array itself). If that's unacceptable, you can skip it and do a linear time check with includes on each inner list in the original array.