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

382
Visualizações
JavaScript: Remove duplicates from array of objects

I have an array of data which looks like this.

data = [ 
  { "name": "Apple", "type": "Fruit"}, 
  { "name": "Cabbage", "type": "Vegetable"} , 
  { "name": "Orange", "type": "Fruit"} 
] 

I want to filter out the element which its type already existed. And I want to keep the first element.

E.g. keep Apple instead of Orange

data = [ 
  { "name": "Apple", "type": "Fruit"},
  { "name": "Cabbage", "type": "Vegetable"}
]
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Using Array#filter, you can iterate over the array while updating a Set to keep track of types added:

const data = [ { "name": "Apple", "type": "Fruit"}, { "name": "Cabbage", "type": "Vegetable"}, { "name": "Orange", "type": "Fruit"} ];

const typeSet = new Set();
const res = data.filter(({ type }) => {
  if(typeSet.has(type)) return false;
  typeSet.add(type);
  return true;
});

console.log(res);

about 4 years ago · Juan Pablo Isaza Relatório

0

1) You can filter the result if type already not present in dict using filter and Set as:

data.filter((o) => (dict.has(o.type) ? false : dict.add(o.type, true)))

const data = [
  { name: "Apple", type: "Fruit" },
  { name: "Cabbage", type: "Vegetable" },
  { name: "Orange", type: "Fruit" },
];

const dict = new Set();
const result = data.filter((o) => (dict.has(o.type) ? false : dict.add(o.type, true)));
console.log(result)

2) You can also use for..of and Set as:

const data = [
  { name: "Apple", type: "Fruit" },
  { name: "Cabbage", type: "Vegetable" },
  { name: "Orange", type: "Fruit" },
];

const dict = new Set(), result = [];

for (let o of data) {
  if (!dict.has(o.type)) {
    result.push(o);
    dict.add(o.type);
  }
}

console.log(result);

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