We can do so by making use of Array.some and Set.
The short version is this
const hasDuplicate = obj.test.some(element =>idSet.size === idSet.add(element.id).size)
A simplyfied example
const myArray = [{"id": 5},{"id": 6},{"id": 7},{"id": 7},{"id": 8}];
var idSet = new Set();
const hasDuplicate = myArray.some(element =>idSet.size === idSet.add(element.id).size);
// elements are added until the first duplicate was found;
// that is the reason why id=8 is not in the set
let allEntries = "";
for (const entry of idSet.entries()) {
allEntries += entry + ", "
}
console.log(allEntries);
Your example with console.log to illustrate what goes on
const obj = { "test": [
{ "id": 7, "num": 112},
{ "id": 8, "num": 11},
{ "id": 3, "num": 10 },
{ "id": 3, "num": 12 },
{ "id": 9, "num": 12 }
]};
const idSet = new Set(); // a Set stores unique values of any type
// for each element in test[] try to add the id to idSet
const hasDuplicate = obj.test.some(element => {
console.log("id ", element.id, " is already in set: ", idSet.has(element.id));
// returns true for the first duplicate and terminates .some()
return (idSet.size === idSet.add(element.id).size)
});
console.log("hasDuplicate =", hasDuplicate); // returns true for 2nd id = 3
What we are trying to achieve here is
- we try to add each object from the
obj.test array into the Set idSet
- every entry within the Set element must be unique.
If and when duplicated ids are found, it cannot be added to the Set. Therefore, the size of the Set, unique, will not increase for that iteration, and thus, it will cause Array.some() to return true, which denotes that there is indeed a duplicated id.
idshould not repeat if so it should return an errorforloop and add eachidto an array or aSet. Check if the currentidin context exists in the array. Have you tried anything? Please read How much research effort is expected of Stack Overflow users?