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

134
Visualizações
Trying to find filter an array to not show duplicates

Trying to find the flaw in my logic. I have a slice of state called companies that is initialized to an empty array:

const [companies, setCompanies] = useState([]);

I have my data coming in which is an array of objects with company data in it. I want to push the company names to the companies state but check if the name already exists there. This is the solution I came up with but for some reason I keep getting each item to show up in the state array even if it already exists.

// Data is an array of objects containing company data including the company name (companyName)

// State
const [companies, setCompanies] = useState([]);
 
useEffect(() => {
    const companyNames = data.map(app => app.companyName);
    const filteredName = companyNames.filter(name => companies.includes(name) === false);
    setCompanies(filteredName);
}, [data])
  
// Expected Output ==> [array with no repeating names]
  
// Current OutPut ==> [all names even if they appear more than once]
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

The javascript set object is tailor-made for this.

see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

// Use to remove duplicate elements from the array

const numbers = [2,3,4,4,2,3,3,4,4,5,5,6,6,7,5,32,3,4,5]

console.log([...new Set(numbers)])

// [2, 3, 4, 5, 6, 7, 32]

about 4 years ago · Juan Pablo Isaza Relatório

0

You could filter the array before you process it to get only unique values, like so:

[1,2,3,2,4,3,1].filter((el, index, arr) => arr.indexOf(el) === index) // yields [1,2,3,4]

or use a Javascript Set.

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