Home > Software design >  Compare 3 arrays and find common elements between 2 and 3 arrays
Compare 3 arrays and find common elements between 2 and 3 arrays

Time:11-12

I have theses arrays

fiveBuy= [1, 2, 3, 4, 5, 6, 7, 8, 10,41]

fifteenBuy  = [1, 4, 3, 0, 99, 10, 23]

thirtyBuy = [3, 41, 1, 0, 10 , 23]

And i want to compare and find the element at least repeated in two of these arrays

This is the function that i return common elements between 3 arrays But now i want to return the common elements between 2 arrays of these arrays 3 common elements in them.

var buyArray = [];
for (let i = 0; i < fiveBuy.length; i  ) {
    const e = fiveBuy[i];
      for (let j = 0; j < fifteenBuy.length; j  ) {
        const el = fifteenBuy[j];
        for (let k = 0; k < thirtyBuy.length; k  ) {
            const ele = thirtyBuy[k];
            if(e == el && e == ele){
              buyArray.push(e);
            }
        }        
      }
  }
//current output  : [1,3,4,10]

So how can i return this output ?

Result = [1,3,4,10,0,23,41]

CodePudding user response:

Here's a one-liner solution:

let fiveBuy = [1, 2, 3, 4, 5, 6, 7, 8, 10, 41];
let fifteenBuy = [1, 4, 3, 0, 99, 10, 23];
let thirtyBuy = [3, 41, 1, 0, 10, 23];

const findCommon = (min, ...arrs) => [...new Set(arrs.flat())].filter(e => arrs.reduce((acc, cur) => acc   cur.includes(e), 0) >= min);

// the first argument is the minimum arrays an element has to be appearing
console.log(findCommon(2, fiveBuy, fifteenBuy, thirtyBuy));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related