skip to Main Content

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


  1. const result = arrobj.every(item => item.cid === arrobj[0].cid);
    
    Login or Signup to reply.
  2. You can check if every cid is equal to any other cid in your array (e. g. arrayobj[0].cid). If that’s the case you know they are all equal regardless of their value.

    arrobj.every(e => e.cid === arrobj[0].cid);
    

    This is how you could do it iterating manually using a for:

    var arrobj = [
      {cid: 109, aid: 220},
      {cid: 109, aid: 221}
    ];
    
    const sameCid = array => {
      let result = true;
    
      for (let i = 1; i < array.length; i++) {
        if (array[i].cid !== array[0].cid) {
          result = false;
          break;
        }
      }
    
      return result;
    };
    
    console.log(sameCid(arrobj));
    Login or Signup to reply.
  3. 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:

    function hasDuplicateCid(arr) {
        const cidSet = new Set();
    
        for (const obj of arr) {
            if (cidSet.has(obj.cid)) {
                return true;
            }
            cidSet.add(obj.cid);
        }
    
        return false;
    }
    
    const arrobj = [{"cid": 109, "aid": 220}, {"cid": 109, "aid": 221}];
    
    const hasDuplicate = hasDuplicateCid(arrobj);
    console.log(hasDuplicate); // Output: true

    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. 😉

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search