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

269
Visualizações
Array Operations: Which way you will prefer, why? is there any better way?

To check if an element exist in an array, which method is better? Are there any other ways to do a boolean check?

type ObjType = {
    name: string
}

let privileges: ObjType[] = [{ name: "ROLE_USER" }, { name: "ROLE_ADMIN" }, { name: "ROLE_AUTHOR" }];

//method 1
const hasAdminPriv = privileges instanceof Array && privileges.find((ele: ObjType) => ele.name === "ROLE_ADMIN");


//method 2
const found = privileges instanceof Array && privileges.find((ele: ObjType) => ele.name === "ROLE_ADMIN") !== undefined;


//method 3
const privilSet = new Set<string>();
privileges.forEach((element: ObjType)=> privilegeSet.add(element.name));

//method 4
const privilegeSet2 = new Set<string>(privileges.map((element: ObjType) => element.name));
console.log(privilegeSet2.has("ROLE_ADMIN"));
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

That most likely depends on the way you want to use this.

The set conversion could be benefical, if you intend to query for multiple things at a time.

Maybe you'd rather use some for your query, if you're really only interested if a value is in the array and not for the rest of the object.

I'd also suggest having a look at includes as that can be exactly what you're looking for at least for trivial objects in an array.

That being said, if forced to use one of the provided methods, I'd argue that method 2 is best if you want to check for one value and method 4 if you either want to query multiple values or can cache the generated set for big arrays and relatively often asked queries.

Side note:

If your whole code is in typescript, I don't really see why you would use privileges instanceof Array. Of course this may be necessary if the array comes from some js code or a file, but even then I'll argue that you should check the type when you receive the array and than assume that it is an array if it is typed that way.

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