0

I want to delete duplicate in array of objects but not as I found in stackoverflow questions,I want to check more than one property and verify that is not duplicate,for example :

 const input =  [
        {
          "eventUid": "0fdb73d9-629f-4151-acab-7b48c24ef2D0",
          "name": "John",
          "lastName": "Doe",
          "city": "Ukraine",
         
        },
        {
          "eventUid": "0fdb73d9-629f-4151-aBab-7b48c24ef2e0",
          "name": "Marcel",
          "lastName": "Pilate",
          "city": "Ukraine",
        },
        {
          "eventUid": "0fcc73d9-629f-4151-aBab-7b48c24ef2e0",
          "name": "John",
          "lastName": "Doe",
          "city": "Ukraine",
        }
      ]

Output shoukd be :

const input =  [
        {
          "eventUid": "0fdb73d9-629f-4151-acab-7b48c24ef2D0",
          "name": "John",
          "lastName": "Doe",
          "city": "Ukraine",
         
        },
        {
          "eventUid": "0fdb73d9-629f-4151-aBab-7b48c24ef2e0",
          "name": "Marcel",
          "lastName": "Pilate",
          "city": "Ukraine",
        }
      ]

Because I want to check name,lastName and city for each element of the array, if there are duplicate then keep only the first. Have you any idea how to check that ?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
alainber82
  • 111
  • 5

1 Answers1

2

You can combine Array.prototype.filter and Array.prototype.findLastIndex.

The concept is that, while iterating the items, if the current index is equal to the last index then it exists twice, thus it can be removed.

Since you are comparing objects, and you want to check only 3 properties out of 4, you cannot use lastIndexOf. But instead you want to search the last index in the array with findLastIndex.

const filtered = 
  input.filter((item, index) => 
    input.findLastIndex(innerItem => 
        innerItem.name === item.name && 
        innerItem.lastName === item.lastName && 
        innerItem.city === item.city
    ) === index);

const input = [{
          "eventUid": "0fdb73d9-629f-4151-acab-7b48c24ef2D0",
          "name": "John",
          "lastName": "Doe",
          "city": "Ukraine",
         
        },
        {
          "eventUid": "0fdb73d9-629f-4151-aBab-7b48c24ef2e0",
          "name": "Marcel",
          "lastName": "Pilate",
          "city": "Ukraine",
        },
        {
          "eventUid": "0fcc73d9-629f-4151-aBab-7b48c24ef2e0",
          "name": "John",
          "lastName": "Doe",
          "city": "Ukraine",
        }
      ];
      
const filtered = input.filter((item, index) => input.findLastIndex(innerItem => innerItem.name === item.name && innerItem.lastName === item.lastName && innerItem.city === item.city) === index)

console.log(filtered);