0

How to remove duplicate dictionary from array of dictionary.

Response:

[  
   {  
      "voter_id":1
   },
   {  
      "passport":1
   },
   {  
      "pan_card":1
   },
   {  
      "aadhaar_card":1
   },
   {  
      "voter_id":1
   },
   {  
      "aadhaar_card":1
   }
]

We need a output like below

[  
       {  
          "passport":1
       },
       {  
          "pan_card":1
       },
       {  
          "aadhaar_card":1
       },
       {  
          "voter_id":1
       }

    ]

I am trying this link but does not helping me..

Swift 3.0 Remove duplicates in Array of Dictionaries

rmaddy
  • 314,917
  • 42
  • 532
  • 579
karthikeyan
  • 3,821
  • 3
  • 22
  • 45

2 Answers2

3

Just convert the array of [String: Int] to Set

var foo = [
[
    "voter_id":1
],
[
    "passport":1
],
[
    "pan_card": 1
],
[
    "aadhaar_card":1
],
[
    "voter_id":1
],
[
        "aadhaar_card":1
    ]
]
Set(foo) // Usage 
Mohmmad S
  • 5,001
  • 4
  • 18
  • 50
  • order will change right if use Set – karthikeyan Jul 01 '19 at 05:18
  • Yes, Set is not sorted in anyway sometimes they remain the same order sometimes they don't however if it was response to decode order wont be matter in any matter, i thought the question without regarding the order, however hope this would help either now or in the future, i also recommend reading about the data structures in swift, would save you plenty of headache – Mohmmad S Jul 01 '19 at 05:20
  • no problem, good luck – Mohmmad S Jul 01 '19 at 05:48
1

Try this if you want to remove duplicated keys

func removeDuplicate(list: [[String:Any]]) -> [[String:Any]] {
    var alreadyKnowKeys: [String] = []
    var newArray: [[String:Any]] = []

    list.forEach { (item) in
        if let key = item.keys.first {
            if !alreadyKnowKeys.contains(key) {
                newArray.append(item)
                alreadyKnowKeys.append(key)
            }
        }

    }

    return newArray
}

Mohmmad S
  • 5,001
  • 4
  • 18
  • 50
Thanh Vu
  • 1,599
  • 10
  • 14