Reputation: 31
I have array of dictionary. If duplicate data is present in the array of dictionary then a flag to be raised with the element name which is duplicate.
The array of dictionary is below:
[[project_code: 1, lob: lob_1], [project_code: 1, lob: lob_1], [project_code: 2, lob: lob_1], [project_code: 3, lob: lob_1]]
Here we need to loop through and find if same project_code and lob is same, then it would return which all project_code which are duplicate.
Duplicate data means the pair of project_code and lob value should be same.
In the above array, if we go through then it should return project_code : 1
If anyone can write a code in Swift ..
Thanks in Advance.
Upvotes: 0
Views: 1858
Reputation: 1461
By using extension
:
extension Array {
var isContainedDuplicateData: Bool {
for (var i = 0 ; i < self.count; ++i){
for (var j = i+1 ; j < self.count; ++j){
let p = self[i] as? NSDictionary
let q = self[j] as? NSDictionary
if (p == q ){
return true
}
}
}
return false
}
}
var duplicateData: AnyObject {
for (var i = 0 ; i < self.count; ++i){
for (var j = i+1 ; j < self.count; ++j){
let p = self[i] as? NSDictionary
let q = self[j] as? NSDictionary
if (p == q ){
return p!
}
}
}
return NSNull()
}
Then write the following code:
var arr: Array = [["a" : "b"], ["b": "c"],["a": "b"],"s"]
var status = arr.isContainedDuplicateData
var duplicatedata = arr.duplicateData
The result is:
status = false
duplicatedata = ["a": "b"]
Upvotes: 2
Reputation: 31311
Here you go,
var dic1 = ["project_code":1, "lob": "lob_1"]
var dic2 = ["project_code":1, "lob": "lob_1"]
var dic3 = ["project_code":2, "lob": "lob_1"]
var dic4 = ["project_code":3, "lob": "lob_1"]
var hasDuplicates = NSArray(objects: dic1,dic2,dic3,dic4)
var duplicates = NSMutableArray()
var noDuplicates = NSMutableArray()
for dics in hasDuplicates{
if noDuplicates.containsObject(dics){
if !duplicates.containsObject(dics){
duplicates.addObject(dics)
}
}
else{
noDuplicates.addObject(dics)
}
}
println(duplicates)
println(noDuplicates)
//to find the duplicate items key
for dics in duplicates{
println(dics["project_code"])
}
Upvotes: 1