-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathContainsObjectInArray.ts
More file actions
23 lines (19 loc) · 880 Bytes
/
ContainsObjectInArray.ts
File metadata and controls
23 lines (19 loc) · 880 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
interface IPersonModel {
name: string;
}
const personObj: IPersonModel = { name: "shubham"}; // Array 1
const personArray1: IPersonModel[] = [{ name: "shubham"}, { name: "ayush" }, { name: "nayan" }]; // Array 2
const personArray2: IPersonModel[] = [{ name: "rohan" }, { name: "nayan" }, { name: "ayush" }]; // Array 3
// Check whether the object is present in the given array or not
const containsObjectInArray = <T, U extends keyof T>(obj: T, list: T[], key: U): boolean => {
for (const item of list) {
if (item && item[key] === obj[key]) {
return true;
}
}
return false;
}
const resultOne = containsObjectInArray<IPersonModel, "name">(personObj, personArray1, "name");
const resultTwo = containsObjectInArray<IPersonModel, "name">(personObj, personArray2, "name");
console.log(resultOne); // True
console.log(resultTwo); // False