Home > database >  How check if there is no duplicate values for a list of properties in an object in javascript
How check if there is no duplicate values for a list of properties in an object in javascript

Time:04-03

const arr = \["key1", "key2", "key3"\];

example 1 :

const obj = {key1 : "1", key2 : "2", key3 : "2", key4: "4", key5 : "5"};

example 2

const obj = {key1 : "1", key2 : "2", key3 : "3", key4: "4", key5 : "1"};

I just want to know if there are duplicatevalue in my object for the key in arr

so for for example 1 it should return true because key2 & key3 are identical and for example 2 it should return false because key1, key2 & key3 are different

what's the easiest way to do it in pure javascript (ecmascript)?

CodePudding user response:

You need to loop in a nested manner and see whether there are duplicates

const obj1 = {key1 : "1", key2 : "2", key3 : "2", key4: "4", key5 : "3"};
const obj2 = {key1 : "1", key2 : "2", key3 : "3", key4: "4", key5 : "5"};

function hasDuplicate(obj) {
    let keys = Object.keys(obj);
    for (let i = 0; i < keys.length; i  ) {
        for (let j = i   1; j < keys.length; j  ) {
            if (obj[keys[i]] === obj[keys[j]]) return true;
        }
    }
    return false;
}

console.log(hasDuplicate(obj1));
console.log(hasDuplicate(obj2));

CodePudding user response:

  • Using Object#entries, get the list of object key-value pairs
  • Using Array#filter and Array#includes, get the pairs which keys are included in the list
  • Using Array#map, get the values of the above filtered pairs
  • Using Set, you can compare the length of the keys to that of unique values above

const keysHaveDuplicateValues = (keys = [], obj = {}) => {
  const keyValues = Object.entries(obj)
    .filter(([ key ]) => keys.includes(key))
    .map(([ key, value ]) => value);
  return keys.length === ( new Set(keyValues) ).size;
}

const 
  keys = ["key1", "key2", "key3"],
  obj1 = {key1 : "1", key2 : "2", key3 : "2", key4: "4", key5 : "5"},
  obj2 = {key1 : "1", key2 : "2", key3 : "3", key4: "4", key5 : "1"};
console.log( keysHaveDuplicateValues(keys, obj1) );
console.log( keysHaveDuplicateValues(keys, obj2) );

Another solution to directly return false when iterating to an existing value:

const keysHaveDuplicateValues = (keys = [], obj = {}) => {
  const set = new Set();
  for(let [key, value] of Object.entries(obj)) {
    if(keys.includes(key)) {
      if(!set.has(value)) {
        set.add(value);
      } else {
        return false;
      }
    }
  }
  return true;
}

const 
  keys = ["key1", "key2", "key3"],
  obj1 = {key1 : "1", key2 : "2", key3 : "2", key4: "4", key5 : "5"},
  obj2 = {key1 : "1", key2 : "2", key3 : "3", key4: "4", key5 : "1"};
console.log( keysHaveDuplicateValues(keys, obj1) );
console.log( keysHaveDuplicateValues(keys, obj2) );

  • Related