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

222
Visualizações
Efficient way to get unique objects from array of objects, by object property?

Here is my array of objects

const array = [ 
  {id: 1, data: "foo"}, 
  {id: 1, data: "bar"}, 
  {id: 2, data: "baz"} 
]

I want to remove all duplicate objects by its id and return only the array of objects that have an unique id.

Expected result:

[ 
  {id: 2, data: "baz"} 
]

This is what I have now: O(n^2)

function getUnique(array) {
    const newArray = []

    for (let obj of array) {
        if (array.filter(x => x.id === obj.id).length === 1) {
            newArray.push(obj)
        }
    }

    return newArray
}

Whats the more efficient way to achieve this?

Is it possible to get the time-complexity to O(n) or O(n log n)?

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

0

const array = [{
        id: 1,
        data: "foo"
    },
    {
        id: 1,
        data: "bar"
    },
    {
        id: 2,
        data: "baz"
    }
]

let map = {};

array.forEach(x => {
    map[x.id] = (map[x.id] || 0) + 1
});

console.log(array.filter(x => map[x.id] === 1))

about 4 years ago · Juan Pablo Isaza Relatório

0

I would suggest to count the number of occurrences in your array and store them in a Map. Next you filter all element, which count is 1

function getUnique(arr) {
  const count = new Map();

  arr.forEach((element) => {
    count.set(element.id, (count.get(element.id) || 0) + 1);
  });

  return array.filter((element) => {
    return count.get(element.id) === 1;
  });
}

This has a runtime of 2(n) since you have to iterate over them twice

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