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"));
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.