Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

267
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda