Home > Software engineering >  How to remove duplicate value from object in Javascript
How to remove duplicate value from object in Javascript

Time:08-16

let obj = { T: 1, h: 1, i: 3, s: 3, t: 1, r: 1, n: 1, g: 1 };

In the given object we have 2 keys(i & s both have same value 3) contains same value. I need to keep one key/value pair and another wants to remove.

How we can achieve this?

CodePudding user response:

You could use a simple reduce function. This will remove duplicates based on the value.

const obj = { T: 1, h: 1, i: 3, s: 3, t: 1, r: 1, n: 1, g: 1 };

const seen = {};
const result = Object.entries(obj).reduce((result, [key, value]) => {
  if (seen[value]) {
    return result;
  }
    
  seen[value] = key;
  
  return {
     ...result,
     [key]: value
  };
}, {}))

console.log(result); // { T: 1, i: 3 }

CodePudding user response:

Make a copy and leave one field out?

let obj2 = { T: obj.T, h: obj.h, i: obj.i, t: obj.t, r: obj.r, n: obj.n, g: obj.g };

;-)

It's not super clear if you want to omit all keys with duplicate values or just some keys. In case you want the latter, here's a reusable function for that:

function copyWithout(source, ...keysToOmit) {
  return Object.entries(source).reduce(
    (accumulator, [key, value]) => {
      return keysToOmit.includes(key)
        ? accumulator
        : Object.assign(accumulator, { [key]: value });
    },
    Object.create(null) // or just {}
  );
}

And use it like so:

copyWithout(obj, 'i');

Can be used to omit multiple keys as well:

copyWithout(obj, 'i', 't', 'r');

CodePudding user response:

You can loop over object keys and add values in some temp array. Verify from that temp array and if value already exist in it then delete that key from object. Try like below.

let obj = { T: 1, h: 1, i: 3, s: 3, t: 1, r: 1, n: 1, g: 1 };
let val = [];

// loop over keys and verify that if value is repeating then delete that key from object.
Object.keys(obj).forEach(k => {
    if (val.includes(obj[k])) {
        delete obj[k];
    } else {
        val.push(obj[k])
    }
});

console.log(obj);


Alternatively if you wish to keep your object as it is and want output in another object then try like below.

let obj = { T: 1, h: 1, i: 3, s: 3, t: 1, r: 1, n: 1, g: 1 };
let val = [];
let newObj = {};

// loop over keys and verify that if value is repeating then delete that key from object.
Object.keys(obj).forEach(k => {
    if (!Object.values(newObj).includes(obj[k])) {
        newObj[k] = obj[k];
    }
});

console.log('newObj', newObj);
console.log('obj', obj);

CodePudding user response:

You can use the following and swap key values twice,

let obj = { T: 1, h: 1, i: 3, s: 3, t: 1, r: 1, n: 1, g: 1 };
function swapKV(ob) {
    return Object.entries(ob).reduce((p,[key,value]) => ({...p,[value]: key}),{})
}
swapKV(swapKV(obj))

CodePudding user response:

You could save all unique values in set. This is the most optimal solution since it takes O(n) in time.

let obj = { T: 1, h: 1, i: 3, s: 3, t: 1, r: 1, n: 1, g: 1 };
    
function removeDuplicateValues(obj) {
  const uniqueValues = new Set();
  const uniquePairs = {};
  Object.keys(obj).forEach(key => {
    const curValue = obj[key];
    if (!uniqueValues.has(curValue)) {
      uniqueValues.add(curValue);
      uniquePairs[key] = curValue;
    }
  });

  return uniquePairs;
}
console.log(removeDuplicateValues(obj)) // {T: 1, i: 3}

CodePudding user response:

const object = { a: 1, b: 2, c: 3, d: 2, e: 3 };

const removeUniqueValuesFromObject = (object) => {
  const map = new Map();

  // loop through all the attributes on an object
  for (const [key, value] of Object.entries(object)) {
    // check if the value already exists in map, if yes delete the attribute
    if (map.has(value)) {
      delete object[`${key}`];
      continue;
    }

    // if value not found, add it to the map
    map.set(value, key);
  }

  // return the updated object
  return object;
};

const result = removeUniqueValuesFromObject(object);
console.log(result);
  • Related