Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

300
Visualizações
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?

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

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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/lodash@4.17.21/lodash.min.js"></script>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda