How to Find Duplicate Data in a JavaScript Object?

Estimated read time 1 min read

To find duplicate data in a JavaScript object, you can use the reduce method along with an object to keep track of the values you have seen so far. If a value is already in the object, it is a duplicate.

Here’s an example:

function findDuplicates(obj) {
  let duplicates = [];
  let seen = {};
  Object.values(obj).forEach(function(value) {
    if (!seen[value]) {
      seen[value] = true;
    } else {
      duplicates.push(value);
    }
  });
  return duplicates;
}

let obj = {a: 1, b: 2, c: 3, d: 2};
let duplicates = findDuplicates(obj);
console.log("Duplicates: " + duplicates);

In this example, the code defines a function findDuplicates that takes an object obj as an argument. The function uses an object seen to keep track of the values seen so far. If a value is already in the object, it is a duplicate and is pushed into the duplicates array. The function then returns the duplicates array. The code then calls the findDuplicates function with the obj value and logs the result to the console.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply