Ad

How To Match Duplicate Values In Nested Arrays In JS

- 1 answer

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.

Ad

Answer

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))

Ad
source: stackoverflow.com
Ad