How to check if array of object property has same value using javascript
If cid
is same value in array of object, then return true.
note: cid is not always ad 109
might change
var arrobj = [{"cid":109,"aid":220},{"cid":109,"aid":221}]
// I Tried
const result = arrobj.every(e => e.cid);
console.log(result)
3
Answers
You can check if every
cid
is equal to any othercid
in your array (e. g.arrayobj[0].cid
). If that’s the case you know they are all equal regardless of their value.This is how you could do it iterating manually using a
for
:To check if the cid property has the same value in an array of objects using JavaScript, you can iterate through the array and keep track of the unique cid values you encounter. If you find duplicate cid values, then you can return true. Here’s how you can do it:
In this example, the hasDuplicateCid function iterates through the array of objects. It uses a Set to keep track of unique cid values. If it encounters a cid that already exists in the Set, it means there’s a duplicate, and it returns true. Otherwise, if the loop completes without finding duplicates, it returns false.
You can adjust the function name and variable names to fit your codebase. 😉