let testArray: { id: number, name: string }[] = [
{ "id": 0, "name": "name1" },
{ "id": 1, "name": "name2" },
{ "id": 2, "name": "name3" },
{ "id": 3, "name": "name4" },
{ "id": 2, "name": "name3" },
{ "id": 2, "name": "name3" }
];
function hasDupes(array: { id: number, name: string }[]): boolean {
const filteredArray = array.filter((item, index, self) =>
index !== self.findIndex(t => (
t.id === item.id && t.name === item.name
))
);
return filteredArray.length !== array.length;
}
console.log(hasDupes(testArray)); // Output: true
So, filter() is to create an array that only has the duplicates.
findIndex() is to find the index of the first occurrence of each object in the array. If index of the current object is not equal to the first occurrence index, then it is a duplicated.
If the lengths of the original array and the filtered array are different, it indicates that duplicates were found, and the function returns true. Otherwise, it returns false.