List all duplicate values in a nested JavaScript object


Suppose, we have a nested object that contains data about some pets like this −

const pets = {
   owner1: 'Frank',
   owner2: 'Curly',
   owner3: 'Maurice',
   dogs: {
      terriers: {
         name1: 'Fido',
         name2: 'Woofy',
         name3: {
            goodDog: 'Frank',
            badDog: 'Judas',
         }
      },
      poodles: {
         name1: 'Curly',
         name2: 'Fido',
      },
   },
};

We are required to write a JavaScript function that takes in one such object.

The function should locate all the duplicate values that exist in the object, and then the function should return an array that contains all the duplicate values from the object.

So, for this object, the output should be −

const output = ['Frank', 'Curly', 'Fido'];

Example

The code for this will be −

const pets = {
   owner1: 'Frank',
   owner2: 'Curly',
   owner3: 'Maurice',
   dogs: {
      terriers: {
         name1: 'Fido',
         name2: 'Woofy',
         name3: {
            goodDog: 'Frank',
            badDog: 'Judas',
         }
      },
      poodles: {
         name1: 'Curly',
         name2: 'Fido',
      },
   },
};
const recursiveSearch = (obj, map = {}, res = []) => {
   Object.keys(obj).forEach(key => {
      if(typeof obj[key] === "object"){
         return recursiveSearch(obj[key], map, res);
      };
      map[obj[key]] = (map[obj[key]] || 0) + 1;
      if(map[obj[key]] === 2){
         res.push(obj[key]);
      }
   });
   return res;
};
console.log(recursiveSearch(pets));

Output

And the output in the console will be −

[ 'Frank', 'Curly', 'Fido' ]

Updated on: 21-Nov-2020

823 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements