-1

For example i have

var myArray = 
[{
   name: 'tom',
   country: 'america',
   favoriteFood: 'pizza'
},
{
   name: 'gary',
   country: 'france',
   favoriteFood: 'pasta'
},
{
   name: 'tom',
   country: 'america',
   favoriteFood: 'pizza'
},
{
   name: 'lou',
   country: 'brazil',
   favoriteFood: 'fries'
},
{
   name: 'gary',
   country: 'france',
   favoriteFood: 'pasta'
},
{
   name: 'marge',
   country: 'russia',
   favoriteFood: 'steak'
}]

The function should return

[{
   name: 'tom',
   country: 'america',
   favoriteFood: 'pizza'
},
{
   name: 'gary',
   country: 'france',
   favoriteFood: 'pasta'
},
{
   name: 'tom',
   country: 'america',
   favoriteFood: 'pizza'
},
{
   name: 'gary',
   country: 'france',
   favoriteFood: 'pasta'
}]

I've tried numerous solutions from this site, however, i have yet to find something that will just return the values that are duplicated (culling the unique values). It is a bit difficult though, since javascript does not seem to have an integrated way to differentiate two objects, even if they have identical values.

Thanks for any help.

Robby Hoover
  • 71
  • 1
  • 11
  • _"I've tried numerous solutions from this site"_... such as? If you don't want this closed as a duplicate you should include your attempts and explain how the solutions did not work – Phil Nov 22 '22 at 06:00
  • Have you checked [how-to-remove-all-duplicates-from-an-array-of-objects](https://stackoverflow.com/questions/2218999/how-to-remove-all-duplicates-from-an-array-of-objects) – flyingfox Nov 22 '22 at 06:04

1 Answers1

1
  1. Build a hashing function for your objects. Something that can take one of your objects and produce a single comparable, identifying value.
  2. Create a map of hashed values to counts of occurrence
  3. Filter the array to only include items with more than one occurrence

const myArray = [{"name":"tom","country":"america","favoriteFood":"pizza"},{"name":"gary","country":"france","favoriteFood":"pasta"},{"name":"tom","country":"america","favoriteFood":"pizza"},{"name":"lou","country":"brazil","favoriteFood":"fries"},{"name":"gary","country":"france","favoriteFood":"pasta"},{"name":"marge","country":"russia","favoriteFood":"steak"}];

const hash = ({ name, country, favoriteFood }) =>
  `${name}:${country}:${favoriteFood}`;

const counts = myArray.reduce((map, item) => {
  const key = hash(item);
  return ({
    ...map,
    [key]: (map[key] ?? 0) + 1,
  });
}, {});
console.log("counts:", counts);

const onlyDupes = myArray.filter((item) => counts[hash(item)] > 1);

console.info(onlyDupes);
.as-console-wrapper { max-height: 100% !important; }

Time complexity: O(n)

Phil
  • 157,677
  • 23
  • 242
  • 245