Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

256
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!