Home > Software engineering >  How to match duplicate values in nested arrays in JS
How to match duplicate values in nested arrays in JS

Time:03-19

I have an array which contains nested arrays that are dynamically created, it looks like this:

[['1', '2'],['1','3', '4'],['1', '3']]

I am trying to implement AND logic by getting only duplicate values from these arrays. My expected output here would be ['1'] since all nested arrays must contain the same value.

// [['1', '2'],['1','3', '4'],['1', '3']]
const arrays = [...new Set(response)].filter(newSet => newSet.length > 0);

const builder = []; // array of all the id's no longer needed

// [[],[],[]]
arrays.forEach(arr => {
    // []
    arr.forEach(value => {
        // [[], [], []]
        const found = arrays.filter(a => a.find(v => v === value));

        if (found.length === 0)
            builder.push(value);
        });
});

console.log(builder); // empty []

This gives me an empty array because of the filter(). How could I return an array of values that all (3 in this case but could be more) arrays contain?

Expected output with the above input would be ["1"]. Any help appreciated.

CodePudding user response:

from what I understand you need the common elements from all array

let response1 = [['1', '2'],['1','3', '4'],['1', '3']]
let response2 = [['1', '2', '3'],['1','3', '4'],['1', '3']]


const getCommon = res => [...new Set(res.flat())].filter(a => res.every(c => c.includes(a)));

console.log(getCommon(response1))
console.log(getCommon(response2))

UPDATE Apparently the set transformation is unnecessary since anyway it has to give the elements common to every array so filtering from res[0] should do

let response1 = [['1', '2'],['1','3', '4'],['1', '3']]
let response2 = [['1', '2', '3'],['1','3', '4'],['1', '3']]


const getCommon = res => res[0].filter(a => res.every(c => c.includes(a)));

console.log(getCommon(response1))
console.log(getCommon(response2))

CodePudding user response:

You can make a count object that has the frequency of each number in it, and just check if the frequency of a number is equal to the length of the original array.

const getIntersectVals = (arrayOfVals)=>{
  const freqs = {};

  for(let arr of arrayOfVals){
    for(let val of arr){
        if(freqs[val]) freqs[val]  ;
        else freqs[val] = 1;
    }
  }
  const uniqueVals = Object.keys(freqs);
  const correctVals = uniqueVals.filter(elem=>{
    return freqs[elem] === arrayOfVals.length;
  })
  return correctVals;
}


const arrayOfVals = [['1', '2'],['1','3', '4'],['1', '3']];

console.log(getIntersectVals(arrayOfVals))

CodePudding user response:

Lodash intesection if you don't mind

const arrayOfVals = [['1', '2'],['1','3', '4'],['1', '3']];

const result = _.intersection(...arrayOfVals);

console.log(result);
.as-console-wrapper{min-height: 100%!important; top: 0}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

  • Related