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

472
Visualizações
Javascript:Delete duplicate in 2D Array

I have a 2D array like this one in JavaScript:

result=[["user1", "java"], ["user2", "python"],["user1", "java"], ["user1", "C++"], ["user1", "java"], ["user2", "Python"]....]  

you can see that ["user1", "java"] comes 3 times and ["user2", "python"] 2 times.

I want to clean this array so that every couple of element must appear only once.it means that if "user1" can appear again, it should be with another language but not with "java". can some one help me?

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

0

You could try this one:

let result= [
  ["user1", "java"], 
  ["user2", "python"],
  ["user1", "java"], 
  ["user1", "C++"], 
  ["user1", "java"], 
  ["user2", "Python"]
];
const map = new Object();
result.forEach((item) => {
  if(!map[item[0]]){
    map[item[0]] = new Array();
  }
  const user = map[item[0]];
  const language = (item[1] || '').toLowerCase().trim();
  if(user.indexOf(language) < 0){
    user.push(language);
  }
});
result = new Array();
Object.keys(map).forEach((user) => {
  map[user].forEach((language) => {
    result.push([user,language]);
  });  
});
console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

You can create a Set out of the array by joining the user and language strings, which would remove the duplicates. And then simply split the strings back to get the desired array.

const 
  result = [["user1", "java"], ["user2", "python"], ["user1", "java"], ["user1", "c++"], ["user1", "java"], ["user2", "python"]],
  uniques = Array.from(new Set(result.map((res) => res.join("-")))).map(
    (data) => data.split("-")
  );

console.log(uniques);

Relevant Documentations:

  • Array.from
  • Set
  • Array.prototype.map
  • Array.prototype.join
  • String.prototype.split
about 4 years ago · Juan Pablo Isaza Relatório

0

You can do this with a single loop over the array using reduce, join and Set as:

const result = [
    ['user1', 'java'],
    ['user2', 'python'],
    ['user1', 'java'],
    ['user1', 'C++'],
    ['user1', 'java'],
    ['user2', 'python'],
];

const [uniqueElements] = result.reduce((acc, curr) => {
        const [uniq, set] = acc;
        if (!set.has(curr.join(','))) {
            set.add(curr.join(','));
            uniq.push(curr);
        }
        return acc;
    },
    [[], new Set()],
);

console.log(uniqueElements);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

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