Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to match duplicate values in nested arrays in JS

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading