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
  • 307,833
  • 40
  • 508
  • 550
Karthi Keyan
  • 195
  • 1
  • 11

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
  • 4,815
  • 3
  • 16
  • 47
  • order will change right if use Set – Karthi Keyan 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
  • 4,815
  • 3
  • 16
  • 47
Thanh Vu
  • 1,549
  • 9
  • 12