0

I am looking for a simple function in js (if possible in Es6 version) to retrieve all the duplicates of an array of objects on the value of email only for example:

    const array = [
  {id: 1, email: 'test1@exemple.fr', nom: 'nom'},
  {id: 2, email: 'test2@exemple.fr', nom: 'nom'},
  {id: 3, email: 'test3@exemple.fr', nom: 'nom'},
  {id: 4, email: 'test@exemple.fr', nom: 'nom'},
  {id: 5, email: 'test4@exemple.fr', nom: 'nom'},
  {id: 6, email: 'test5@exemple.fr', nom: 'nom'},
  {id: 7, email: 'test6@exemple.fr', nom: 'nom'},
  {id: 8, email: 'test@exemple.fr', nom: 'nom'},
  {id: 9, email: 'test@exemple.fr', nom: 'nom'},
  {id: 10, email: 'test@exemple.fr', nom: 'nom'},
  {id: 11, email: 'test2@exemple.fr', nom: 'nom'},
  {id: 12, email: 'test2@exemple.fr', nom: 'nom'},
]

And the result I want to get is this:

return = [
  {id: 8, email: 'test@exemple.fr', nom: 'nom'},
  {id: 9, email: 'test@exemple.fr', nom: 'nom'},
  {id: 10, email: 'test@exemple.fr', nom: 'nom'},
  { id: 11, email: 'test2@exemple.fr', nom: 'nom'},
  {id: 12, email: 'test2@exemple.fr', nom: 'nom'}
]

Thank you for your help :)

sakura
  • 44
  • 8
  • 2
    Use an object to count the duplicates of each email. Then filter the array to just the ones where the count is more than 1. – Barmar Apr 26 '22 at 17:47
  • 2
    Can you include code where you've attempted a solution so we can help you further? – Jeff LaFay Apr 26 '22 at 17:51
  • 1
    I don't know why someone closed this question, since duplicated arrays are not the same as duplicated arrays of Objects. – Canilho Apr 26 '22 at 18:02
  • 1
    The best thing you can do is to order the array by the email , to make every repetition next to each other, and then you can read one position at a time, and check if it has exactly the same email as the next one. If they are the same, remove the last element readed, and preceded to read the next one until you get to the end of the list. – Canilho Apr 26 '22 at 18:03
  • Thank you very much I was able to find the solution via the link that the person shared in one of the comments :) and here is the solution ^^: – sakura Apr 26 '22 at 18:06
  • const strArray = array const alreadySeen = []; `strArray.forEach(str => alreadySeen[str.email] ? ok.push(str) : alreadySeen[str.email] = true);` – sakura Apr 26 '22 at 18:06

0 Answers0