What is the best way to return information about duplicates in typescript from a large array of objects (I want it to return true or false).
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" }
];
3
Answers
You can go filter your array and create your ruleset how to identify duplicates and then handle in the way you want.
Example on stackbiz: https://stackblitz.com/edit/stackblitz-starters-8fiqaa?file=src%2Fmain.ts
Good way is when you can implement isEqual() function for your data model, then utilize it for controllable comparison. And it will be located in proper spot together with you data model class.
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.
My approach would be using a
Set
, which would guarantee that no item is a duplicate. Then you could compare the size of your array and your set: